JS code for ajax request
This is because you need to set up CSRF in your AJAX request, same as you'd do in normal request.
Add the following code to your JavaScript:
// This handles generation of CSRF token
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;
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
refer to docs: https://docs.djangoproject.com/en/2.0/ref/csrf/#ajax
I hope this helps.
Good luck!
It is normal, it's beacause of the CSRF token. Try this:
var csrftoken = $('[name="csrfmiddlewaretoken"]').val();
And after include this in your Ajax request
$.ajax({
...
headers: {
'Accept': 'application/json', //if json
'Content-Type': 'application/json', //if json
"X-CSRFToken": csrftoken
},
credentials: 'include',
....
})
It worked for me