I'm doing something pretty simple in Django and I'm getting this really weird error:
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. What's going wrong?
The simplest solution to this problem is to remove the else clause:
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).
如前所述,代码看起来是正确的,因此我希望在发布问题时会丢失一些内容(也许第二个if语句并未真正缩进)。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.