rabbid
rabbid

Reputation: 5735

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"
        post = 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>&#39;PostForm&#39; object has no attribute &#39;cleaned_data&#39;</pre></td>

No attribute cleaned_data? But why...?

Upvotes: 1

Views: 1077

Answers (2)

Sam Dolan
Sam Dolan

Reputation: 32542

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
    ...

Upvotes: 0

Arjen
Arjen

Reputation: 1321

The cleaned_data attribute becomes available after calling is_valid() on a form. You should move cd = form.cleaned_data to below the if.

Upvotes: 4

Related Questions