2👍
Follow django documentation:
add javascript code to your pages to send csrf value with ajax requests:
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');
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);
}
}
});
-1👍
You can use a middleware to avoid csrf checks for all ajax posts, use it before csrf middleware.
class DisableCSRF(object):
def process_request(self, request):
if request.is_ajax():
setattr(request, '_dont_enforce_csrf_checks', True)
Yeah its a quick and dirty solution, but i use it for my rest api backend which doesn’t use cookies.
- [Answer]-Post json to django but get 500 error
- [Answer]-Django-generic-ratings installation gives error: No module named default
Source:stackexchange.com