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

1 comment:

Popular Posts