Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery and Django CSRF Token

I have 2 html Pages.

A Parent Page and a Child Page. The Child Page Contains a Submit Button that runs code on the Parent Page to submit an Ajax message.

I load the child page using $.load() method and then when the button is clicked it runs a $.ajax .POST Method. This post method only passes a JSON String to the Python Code.

When I do this on any browser except IE It works fine. However when I run this code in IE. I get Python / Django Errors about CSRF Tokens.

I Think the reason is because the child page is just a refresh of current page itself with the serverside code being run.

Does anyone know how I should go about getting this to work.

Cheers,

like image 468
TheMonkeyMan Avatar asked Dec 23 '11 10:12

TheMonkeyMan


People also ask

Is CSRF token necessary Django?

Django has a {% csrf_token %} tag that is implemented to avoid malicious attacks. It generates a token on the server-side when rendering the page and makes sure to cross-check this token for any requests coming back in. If the incoming requests do not contain the token, they are not executed.


2 Answers

You are not passing the csrf token with POST. Try doing what I have done in data. That is to fetch the csrf token (or your own method) and pass it in your arguments.

$.ajax({     url : url,     type: "POST",     data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},     dataType : "json",     success: function( data ){         // do something     } }); 
like image 92
Zain Khan Avatar answered Sep 20 '22 11:09

Zain Khan


If you are sending a POST request body it maybe easier to add the csrf token as a request header instead. I find this approach easier to read, as it does not clutter up the request body with a token. Most AJAX request will send the csrf token as a header as suggested by the Django documentation.

function startTest(testId) {   var payload = JSON.stringify({     test_id : testId   });   $.ajax({     url: "/test-service/",     method: "POST",     headers: {'X-CSRFToken': '{{ csrf_token }}'},     data: payload,     dataType: "json"   }).done(function(response) {     console.log(response.id + " " + response.name);   }).fail(function (error) {       console.log(error);   }); } 
like image 41
MichaelB Avatar answered Sep 17 '22 11:09

MichaelB