4👍
Django in its docs has defined to actually set the header on AJAX request, while protecting the CSRF token from being sent to other domains using settings.crossDomain
in jQuery 1.5.1 and newer.
Acquiring the token:
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
Setting the CSRFToken in the header:
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Also try this method to embed CSRF token in each AJAX request given on this SO link.
$(function () {
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
});
- [Django]-How to get current user id Django
- [Django]-Django Heroku not serving static files when Debug=False
- [Django]-Is sqlite bundled into Django?
Source:stackexchange.com