Jquery – Django CSRF Token without forms

ajaxcsrfdjangojquery

Sounds strange but what about the scenario posting contents with Javascript (for example AJAX) without using a form (could be possible to read several contents from the surface).

Where should I place the csrf_token template tag? I already added the AJAX Fix:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

…but I get the "CSRF verification failed. Request aborted." 404 Error.

Best Answer

You must set a custom HTTP header, X-CSRFToken, in your AJAX request. See: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

If you've already followed that advice, it should be working. Use something like Firebug to monitor the request that's being sent and inspect the headers to ensure that the custom header is truly being passed. If it's not, then check your implementation again to make sure you did it just as the docs describe.

Also note:

Due to a bug introduced in jQuery 1.5, the example above will not work correctly on that version. Make sure you are running at least jQuery 1.5.1.

Related Topic