Skip to content

Instantly share code, notes, and snippets.

@fabiomontefuscolo
Created July 31, 2014 15:09
Show Gist options
  • Save fabiomontefuscolo/51c85ac3f80204272e68 to your computer and use it in GitHub Desktop.
Save fabiomontefuscolo/51c85ac3f80204272e68 to your computer and use it in GitHub Desktop.
Configure jQuery to send 'X-CSRFToken' required by Django. With this piece of code loaded after jQuery, it's not necessary to config headers in every jQuery.post against Django.
(function($){
if(!$) {
return;
}
var match = document.cookie.match(/csrftoken=(\w+)/);
var token = match ? match[1] : '';
$.ajaxSetup({
headers: { 'X-CSRFToken': token }
});
})(window.jQuery);
@fabiomontefuscolo
Copy link
Author

The cookie name may vary according to Django configuration. More details in https://docs.djangoproject.com/en/dev/ref/settings/#csrf-cookie-name.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment