变量的Python范围-赋值前引用错误
产生错误 赋值前引用的局部变量“url” 我在SO中搜索过这个问题,但其中大多数似乎都解决了这样一个事实,即变量是在函数外部声明的,需要全球化,或者变量是在类的成员函数中访问的。这种情况是不同的。我不明白为什么不允许在同一个函数中调用变量的Python范围-赋值前引用错误,python,django,scope,Python,Django,Scope,产生错误 赋值前引用的局部变量“url” 我在SO中搜索过这个问题,但其中大多数似乎都解决了这样一个事实,即变量是在函数外部声明的,需要全球化,或者变量是在类的成员函数中访问的。这种情况是不同的。我不明白为什么不允许在同一个函数中调用url 看看下面的代码,url是否可以在登录函数中的任何位置访问?我相信如果这是C/C++的话,情况就是这样。为什么这有什么不同 代码 def login(request): # #no url declaration here # if req
url
看看下面的代码,url
是否可以在登录函数中的任何位置访问?我相信如果这是C/C++的话,情况就是这样。为什么这有什么不同
代码
def login(request):
#
#no url declaration here
#
if request.POST:
…
url = 'main.login.html'
user = authenticate(username=username,password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
state = 'You are logged in'
url = 'main.home.html'
else:
state = 'You are not logged in due to error'
else:
state = 'Incorrect username or password'
…
render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)
回溯指向最后一行
render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)
在您的代码中,您做了两个更改,它将正常工作。在检查post方法之前定义url,并将return关键字与render_to_响应语句一起使用
def login(request):
url = 'main.login.html'
state = ''
if request.POST:
user = authenticate(username=username,password=password)
if user is not None:
if user.is_active:
auth_login(request, user)
state = 'You are logged in'
url = 'main.home.html'
else:
state = 'You are not logged in due to error'
else:
state = 'Incorrect username or password'
return render_to_response(url,{'state':state,'username':username},context_instance=RequestContext(request)
如果在检查POST方法之前未定义url和状态,则GET请求将引发错误。这两行都不会引发该错误。完整的堆栈跟踪包括行号。检查它。错误指向哪一行?这是
url='main.home.html'
行吗?或者函数前面的某行?将代码缩减到仍然会产生错误的最小示例,然后发布,因为如果省略号真的不相关,就不可能发生这种情况。你能发布整个代码吗?您是否确定第一行url
位于最初的4个空格处?通常的罪魁祸首是在if/else块中混合空格/制表符或仅仅是缩进级别。。如果您的…
部分中有if/else块,请用细齿梳检查。@stackplasm请不要忘记缩进总是4个空格。这是默认的python代码。请通过。