Roshan Book

My Tech Notebook

Django 1-2 csrf verification failed


This post was originally taken from : http://jordanmessina.com/2010/05/24/django-1-2-csrf-verification-failed/

 

Django 1.2 – CSRF verification failed. Request aborted.

I was getting this 403 error today while attempting to make a POST request to a view:
403 Forbidden

CSRF verification failed. Request aborted.
Help

Reason given for failure:

 

CSRF cookie not set.

Hopefully this saves you some time because I sure wasted a lot of mine solving it.  I ended up having to add ‘django.middleware.csrf.CsrfViewMiddleware’, and  ‘django.middleware.csrf.CsrfResponseMiddleware’ to my MIDDLEWARE_CLASSES in settings.py and my problems were solved.  All I had to say was mutha eff.  Django also was no help with their debug.  My MIDDLEWARE_CLASSES now looks like:

MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.middleware.csrf.CsrfResponseMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)

Hope this helps.

Edit 10/29/2010
So I wrote this post back when Django 1.2 was just out as an early beta, there really wasn’t much support around it and this was my quick and dirty solution to make things work without really understanding what was going on. I noticed with analytics that this gets quite a bit of attention daily so I want everyone to know the two other options, and really the more right ways, for getting around this 403 error. Essentially, what you really want to do is put the csrf_token somewhere within your form. This adds a hidden div with the value of the input as the csrf token:

<form action="..." method="POST">{% csrf_token %}
...
</form>

The other option is to wrap the function in the views that’s ultimately throwing this error with the csrf_exempt decorator.


from django.views.decorators.csrf import csrf_exempt
...
@csrf_exempt
def my_func(request):
...

Like I said, these are really the much better options than adding 'django.middleware.csrf.CsrfResponseMiddleware' to your middleware settings.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: