Reputation: 91630
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?
Upvotes: 0
Views: 451
Reputation:
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).
Upvotes: 3