【问题标题】:global name 'request' is not defined [closed]未定义全局名称“请求”[关闭]
【发布时间】:2013-06-20 00:53:22
【问题描述】:

当使用示例 "views.py without functions.py" 时,它工作正常并且会话检查正常,所以它返回用户名。 p>

但是,当使用第二个示例时,with the functions.py,向我显示以下 错误

NameError at /login/

全局名称“请求”未定义

views.py 没有 functions.py

def main(request):
    c = {}
    c.update(csrf(request))

    if request.session.get('username'):
        susername = request.session['username']
    else:
        susername = ""

    return render_to_response("login/login.html",{'username': susername},context_instance=RequestContext(request))

views.py 和 functions.py

def main(request):
    c = {}
    c.update(csrf(request))

    susername = loggedin()


    return render_to_response("login/login.html",{'username': susername},context_instance=RequestContext(request))

functions.py

from django.template import RequestContext

def loggedin():
    if request.session.get('username'):
        susername = request.session['username']
    else:
        susername = ""

    return susername

为什么第二个不起作用,我该如何解决?

谢谢

【问题讨论】:

    标签: python django session


    【解决方案1】:

    考虑一下。请求不作为参数传递,因此在 loggedin() 函数的范围内是未知的。

    你可以像这样简单地传递请求

    susername = loggedin(request)
    

    或者,在这种情况下,只需传递您需要检查的内容。

    susername = loggedin(request.session)
    

    把函数改成

    def loggedin(session):
        return session['username'] if session.get('username') else ''
    

    【讨论】:

    • 已修复。谢谢@Alasdair
    • return session.get('username', '') 会更好,但至少代码现在可以工作了。
    【解决方案2】:

    你写的是一个模板上下文处理器,你应该这样写:

    def loggedin(request):
        return {'username': request.session.get('username','')}
    

    将其保存在一个文件中,并将其添加到settings.pyTEMPLATE_CONTEXT_PROCESSORS'django.core.context_processors.request', 行之后。

    如果您将文件命名为someapp/processors.py,那么您将在元组中添加'somapp.processors.loggedin',

    然后,只要您返回RequestContext 的实例,您的模板中就会包含{{ username }}

    【讨论】:

    • +1 虽然这是一个好方法,但我认为 OP 正在尝试一个简单的教程,他只是忘记将请求对象作为参数发送。
    • +1 哇,这比我想要的要好。实际上,我想知道这在 Python 中是否可行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2018-05-04
    • 2015-12-22
    • 2014-04-18
    相关资源
    最近更新 更多