Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django 1.2.4 CSRF verification failed

Django 1.2 is consistently giving me this CSRF verification error when I perform a POST form. I "think" I've done all the things asked in the Django 1.2 docs, namely,

  1. Ensure MIDDLEWARE_CLASSES is included with 'django.middleware.csrf.CsrfViewMiddleware'

  2. Ensure the {% csrf_token %}

    <form action="/words/new/" method="post">
    {% csrf_token %}
    {{ form.as_p }}
        <input type="submit" value="Enter" />
    </form>
    
  3. Use RequestContext in my response

    def create(request):
        if request.method == 'POST':
            form = DefinitionForm(request.POST)
            if form.is_valid():
                form.save()
            c = {}
            return render_to_response('dict/thanks.html',c, 
                                        context_instance=RequestContext(request))
        else:
            form = DefinitionForm()
        return render_to_response('dict/create_definition.html', {
            'form' : form,
        })
    

Note that the GET action works in this function. So I think I'm using render_to_response right.

I've even tried to throw in the @csrf_protect decorator and even that didn't seem to work. I'm out of ideas and I'm about to choke myself with my laptop.

Any thing you guys can think of?

Thanks!

like image 247
Bryan Avatar asked Jan 23 '11 16:01

Bryan


1 Answers

You're not following #3. The RequestContext must be used with the rendering of the template that shows the form. It's not necessary for the thanks page.

return render_to_response('dict/create_definition.html', {
    'form' : form,
}, context_instance=RequestContext(request))

And as a side note, you should use the PRG pattern instead of rendering the thanks page directly.

like image 70
AndiDog Avatar answered Nov 09 '22 18:11

AndiDog