简体   繁体   English

UnboundLocalError,分配前访问了局部变量,但不是吗?

[英]UnboundLocalError, local variable accessed before assignment, but not?

I'm doing something pretty simple in Django and I'm getting this really weird error: 我正在Django中做一些非常简单的事情,并且遇到了这个非常奇怪的错误:

UnboundLocalError at /me/profile/edit/
local variable 'form' referenced before assignment

Here's my code: 这是我的代码:

if request.method == "POST":
    form = MyForm(request.POST)
    if form.is_valid():
        print "Yes"
else:
    form = MyForm(user=request.user)

Why is this code throwing that error? 为什么这段代码会引发该错误? It's pretty straightforward, yet if I take out the if form.is_valid() stuff, it works. 这很简单,但是如果我取出if form.is_valid()东西,它就可以工作。 What's going wrong? 怎么了

The simplest solution to this problem is to remove the else clause: 解决此问题的最简单方法是删除else子句:

form = MyForm(request.POST or None)

if request.method == 'POST':
    if form.is_valid():
        print 'Yes'

Danny Greenfeld's Advanced Django Form Usage presentation is a great example of this: http://www.slideshare.net/pydanny/advanced-django-forms-usage (slide 33 is what I'm referencing specifically). 丹尼·格林菲尔德(Danny Greenfeld)的“高级Django表单用法”演示文稿就是一个很好的例子: http : //www.slideshare.net/pydanny/advanced-django-forms-usage (幻灯片33是我具体指的)。

如前所述,代码看起来是正确的,因此我希望在发布问题时会丢失一些内容(也许第二个if语句并未真正缩进)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 “UnboundLocalError:分配前引用的局部变量‘status’”和“status_1”未被 Pylance 访问 - "UnboundLocalError: local variable 'status' referenced before assignment" and "status_1" is not accessed by Pylance UnboundLocalError:分配前已引用局部变量“ truebomb” - UnboundLocalError: local variable 'truebomb' referenced before assignment UnboundLocalError:分配前已引用局部变量“ cur” - UnboundLocalError: local variable 'cur' referenced before assignment UnboundLocalError:分配前已引用局部变量“ Counter” - UnboundLocalError: local variable 'Counter' referenced before assignment UnBoundLocalError:赋值之前引用的局部变量(Python) - UnBoundLocalError: local variable referenced before assignment (Python) UnboundLocalError:分配前已引用局部变量“ strdate” - UnboundLocalError: local variable 'strdate' referenced before assignment UnboundLocalError:赋值之前引用了局部变量“ key” - UnboundLocalError: local variable 'key' referenced before assignment unboundLocalError:赋值前引用了局部变量“loopback” - unboundLocalError: local variable 'loopback' referenced before assignment UnboundLocalError:分配前已引用局部变量“ endProgram” - UnboundLocalError: local variable 'endProgram' referenced before assignment UnboundLocalError:赋值前引用了局部变量“Score” - UnboundLocalError: local variable 'Score' referenced before assignment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM