Django CSRF verification failed

Ludovico Fischer

10 Sep 2010

If you migrate to Django 1.2 you might encounter a CSRF Verification failed error when rendering a form.

An interim solution is to enable django.middleware.csrf.CsrfResponseMiddleware:

MIDDLEWARE_CLASSES = (
   # Your other middleware here

'django.middleware.csrf.CsrfResponseMiddleware',
)

CsrfResponseMiddleware is there for legacy compatibility.  If you want to use the features introduced in Django 1.2, CsrfViewMiddleware should take care of all CSRF needs at the middleware level. The new CSRF functionality relies on modifying individual views.

Views in need of CSRF protection should provide a special variable in the template rendering context.

The easiest way to provide this variable is to pass a django.template.RequestContext to the template.  You instantiate a RequestContext by passing the current request (quite logically):

def some_view(request):

        c = RequestContext(request)

If you are using render_to_response, you can pass the context as an extra parameter after the template variable dictionary:

render_to_response('template.html', data_dict, c)

You can also do everything at once:

render_to_response('template.html', data_dict, RequestContext(request))