I was having issues with this for hours on a similar project. I finally found the solution! I hope this information helps. The script I'm using is not on the django template, so using csrfmiddlewaretoken: '{{ csrf_token }}'
wouldn't work for me.
I added in the "credentials": 'same-origin'
as listed above, but also included "X-CSRFToken": getCookie("csrftoken")
, which uses the function included at the bottom. It was this second bit that I needed. So your code should look something like:
fetch("http://127.0.0.1:8000/api/endpoint", {
method: "POST",
body: $("#form").serializeArray(),
credentials: 'same-origin',
headers: {
"X-CSRFToken": getCookie("csrftoken")
}
})
.then(function(data) {
})
.catch(err => console.log(err));
Then you need this function added:
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;}
And of course the method has to be on the same page. Taken from Django Docs.
https://docs.djangoproject.com/en/1.11/ref/csrf/#ajax
I found this information from this post:
https://stackoverflow.com/a/43943556 from user Ska