Django code only works in debug
Very confused about this one. This code in views.py works, but only when I'm debugging using Pycharm. If I just do runserver
I get a 500 error.
views.py:
def add_post(request):
if request.method == 'POST':
form = PostForm(request.POST)
cd = form.cleaned_data
if form.is_valid():
print "valid"
p开发者_如何转开发ost = Post(nickname=cd['nickname'], body=cd['body'], category=cd['category'])
post.save()
return HttpResponse("success")
return HttpResponseServerError("fail")
Error as seen in Chrome Inspector
<th>Exception Value:</th>
<td><pre>'PostForm' object has no attribute 'cleaned_data'</pre></td>
No attribute cleaned_data? But why...?
The cleaned_data
attribute becomes available after calling is_valid()
on a form. You should move cd = form.cleaned_data
to below the if
.
A Django form's cleaned_data attribute isn't accessible until you call is_valid()
on the form.
form = PostForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
...
精彩评论