Last Updated: February 25, 2016
· celc

Setting up jQuery to pass csrf tokens to Django.

  $.ajaxSetup({data: {
    csrfmiddlewaretoken: '{{ csrf_token }}'

This works in every case except when posting a query string type of data like like if you do $.post('/', $('form').serialize()); as jQuery doesn't merge ajaxSetup data with that data.

Alternatively should you need to apply the csrf_token to requests with querystring type data it's possible to do:

  $.ajaxSetup({beforeSend: function(xhr, settings){
                         '{{ csrf_token }}');

1 Response
Add your response


What makes jQuery so great is that they've thought of stuff like this. Great tip.

over 1 year ago ·