cxwg_g
Last Updated: February 25, 2016
·
7.744K
· celc

Setting up jQuery to pass csrf tokens to Django.

<script>
  $.ajaxSetup({data: {
    csrfmiddlewaretoken: '{{ csrf_token }}'
  }});
</script>

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:

<script>
  $.ajaxSetup({beforeSend: function(xhr, settings){
    xhr.setRequestHeader('X-CSRFToken', 
                         '{{ csrf_token }}');
  }});
</script>

1 Response
Add your response

1094

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

over 1 year ago ·