SirDeimos
SirDeimos

Reputation: 93

Firefox Django CSRF token error

I recently made some changes to a form to do some more advanced error checking than celery provides (errors based on input from multiple fields). Everything was working fine until a coworker found that the form didn't work on Firefox anymore (dev and testing done on Chrome).

The specific error being thrown is:

django.request [WARNING] > Forbidden (CSRF token missing or incorrect.): /[url]

I suspect the root of this issue comes from the change:

<form action="{% url '[submit url]' %}"> to <form onsubmit="sendData()"> where sendData constructs an XMLHttpRequest and sends it. I've tried adding csrftoken header to the request from {{csrf_token}} but it fails for the same reason - and even breaks the process on Chrome!

Upvotes: 0

Views: 483

Answers (1)

Wariored
Wariored

Reputation: 1343

The csrf_token should be in your XMLHttpRequest not in the form since you are using JS to send data:

var xhttp = new XMLHttpRequest();
xhttp.open("POST", url, true);
xhttp.setRequestHeader("X-CSRFToken", "{{ csrf_token }}");
xhttp.send();

Upvotes: 1

Related Questions