I've been experimenting with JavaScript's fetch library to perform a form submission on my Django application. Despite my efforts, I keep running into CSRF validation issues.
The Ajax documentation suggests specifying a header, which I have attempted to implement.
I've also tried fetching the token using a templatetag and including it in the form data.
Unfortunately, neither method seems to resolve the problem.
Below is the sample code that includes both the form value and the header:
let data = new FormData();
data.append('file', file);
data.append('fileName', file.name);
// add form input from hidden input elsewhere on the page
data.append('csrfmiddlewaretoken', $('#csrf-helper input[name="csrfmiddlewaretoken"]').attr('value'));
let headers = new Headers();
// add header from cookie
const csrftoken = Cookies.get('csrftoken');
headers.append('X-CSRFToken', csrftoken);
fetch("/upload/", {
method: 'POST',
body: data,
headers: headers,
})
While I have successfully achieved this using jQuery, I wanted to explore the possibility of utilizing fetch
.