8

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!

1
  • Check the HTML in your browser to make sure the csrf token field is in there. Then dump the POST responses to check it gets back to the view.
    – Spacedman
    Jan 23, 2011 at 17:06

1 Answer 1

7

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.

2
  • That is for the GET action. If you look at the code again, I've included that for the condition when request.method == 'POST'.
    – Bryan
    Jan 23, 2011 at 17:10
  • 3
    @bryli: Exactly that's the problem. The CSRF context processor needs the request context when creating the token and putting it in the template context, (probably) not when checking it in the POST.
    – AndiDog
    Jan 23, 2011 at 17:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.