Really disable the cross site request forgery (csrf) middleware in Django

So, I’m using the Django built-in ‘auth’ app in the project I’m working on now, in order to handle the login/logout. My problem is that I want to disable the csrf protection that Django provides by default. So I said “No problem, I’ll just remove the csrf middleware”.

Apparently, this doesn’t cut it for the login app, because if you look in the code of the current version of Django at the moment I’m writing this (1.3.1) for how the @csrf_protect decorator that the login view is using, you’ll notice that it will not take into account if you use the csrf middleware in your project or not, it will just use it anyway.

So, in order to really disable the csrf protection, I found on Stack Overflow the following solution:

You create a middleware.py file in your Django application in which you’ll place the following class:

1
2
3
class DisableCSRF(object):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

Now, you add the above middleware to your project settings at the end of the MIDDLEWARE_CLASSES setting like so:

1
2
3
4
MIDDLEWARE_CLASSES = (
    ...
    '<YOUR_APP_NAME>.middleware.DisableCSRF'
)

Hope this helps! ;)

UPDATE: As Tim rightly pointed out in the comments, you will obviously have to remove {% csrf_token % } from the login template, if you still have it there.

Comments

3 Responses to “Really disable the cross site request forgery (csrf) middleware in Django”
  1. Tim says:

    Thanks for posting this! I had the exact same problem, in addition though I had to remove the {% csrf_token % } from the login template.

  2. ben says:

    Many thanks! Your post really save my life!

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!