How to Add Django CSRF Token to jQuery AJAX Function
In order to successfully send an AJAX POST
or GET
request to your Django application, you will need to supply a CSRF token in the request headers.
To do this we need to add a X-CSRFToken
property to the request header with the value of the csrfmiddlewaretoken
supplied by Django.
The first step is to add the CSRF token in your form using the csrf_token
keyword like this:
myapp/templates/form.html
<form method="POST" action="{{ request.path }}" class="ajax">
{% csrf_token %}
{{form.name}}
<button type="submit">Submit</button>
</form>
Now at the top of your application's .js
file we can add the CSRF token from the above form into any AJAX request using a function like this:
$(function() {
$.ajaxSetup({
headers: {
"X-CSRFToken": $('[name=csrfmiddlewaretoken]').val()
}
})
});
django