I've been trying to solve the same problem, And as arnaud576875 says you have to Add the csrf token header on each ajax request just like the Django docs says https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax And execute that code before any Ajax request you make.
But there is something additional, you have to find a way to load the csrf token to the cookies of your app before trying to do any AJAX request, after a lot of painful hours researching I couldn't find an specific answer of how to do this, what I did found is that to ensure that your view sends the csrf token within a cookie you can use the ensure_csrf_token()
to each view you want to receive the token https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#django.views.decorators.csrf.ensure_csrf_cookie this seems to work for a lot of people, but did not worked for me.
Another way is using the Legacy Method, adding the 'django.middleware.csrf.CsrfResponseMiddleware'
to your MIDDLEWARE_CLASSES
but I don't recommend this method because leaves several security risks.
https://docs.djangoproject.com/en/1.2/ref/contrib/csrf/#legacy-method
All this methods that I said before did not worked for me. The way that I'm allowing Ajax to do some requests is as the following, and if someone finds this a dangerous method please let me know:
- Go to the first view that your user will hit, like the /home/ page.
- Insert this before redirecting or parsing anything
request.META["CSRF_COOKIE_USED"] = True
And that's it, That is the way that works for me, but as I said before I'm not sure if this is the right method or the most secure one to accomplish the csrf protection.