Friday, September 14, 2012

Using jQuery ajax in Django requires {{csrf_token}}

Any data that is sent to a django view/api-function via POST (or even an ajax call for that matter) )will not be accepted and will return an HTTP-500 error unless a csrf-token is also sent with the request. (Just like how we do it when creating a <form> in django).

A quick fix for this is to simply supply the {{ csrf_token }} via the .ajaxSetup() function like so:
$.ajaxSetup({data: {csrfmiddlewaretoken: '{{ csrf_token }}' },});

And then follow with your .post or .ajax function..

Ref: http://stackoverflow.com/a/7715325/1415352

3 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from JQuery Training in Chennai . or learn thru JQuery Training . or learn thru ES6 Online Training. Nowadays JavaScript has tons of job opportunities on various vertical industry.

    ReplyDelete

Popular Posts