Django Book Tutorial doesn’t work – CSRF error


If you’ve been working your way through the Django Book tutorial, you may have run into a spot of trouble with the form chapter. Even though I had basically cut and pasted in the chapter code, I kept getting a CSRF Verification Failed error, which was definitely not listed in the book.

We don't like this.

We don’t like this.

CSRF stands for Cross Site Request Forgery, which is a type of attack on your web page. This occurs when a malicious Web site contains a link, a form button or some javascript that is intended to perform some action on your Web site, using the credentials of a logged-in user who visits the malicious site in their browser. CSRF protection in Django is meant to prevent just that, which is why we get an error if we haven’t properly secured our forms. It seems to have been enforced in newer versions of Django, but still not updated in the online book.

The problem can be solved as follows:

  1. Add the middleware 'django.middleware.csrf.CsrfViewMiddleware' to your list of middleware classes, MIDDLEWARE_CLASSES.
  2. In any template that uses a POST form, use the csrf_token tag inside the html.
    <form action="" method="post">
        	{% csrf_token %}
                {{ form.as_table }}
            <input type="submit" value="Submit">
  3.  Instead of using a context in your forms, use a RequestContext in The code looks like this:
from django.template import RequestContext
def contact(request):
    initialData = {'form': form}
    return render_to_response('contact_form.html', initialData,

The RequestContext contains a CSRF token which is necessary to prevent this error. Completing these steps should resolve the problem! 🙂