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 file in your Django application in which you’ll place the following class:

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:


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.


4 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!

  3. rsm says:

    Yep, really useful!

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!