I'm writing a site using REST API. I use django with piston at backend (also using corsheaders.middleware.CorsMiddleware with CORS_ORIGIN_ALLOW_ALL = True). And I use backbone.js for frontend. I'm sending POST request from client-side and get error:
CSRF verification failed. Request aborted.
I've googled a lot and all solutions suggested something like "Use the render shortcut which adds RequestContext automatically". But I have no view, forms will be requested from frontend, that shouldn't know about how backend works. Here's code of my scipt
Question = Backbone.Model.extend({
urlRoot: 'http://example.com/api/questions',
defaults: {
id: null,
title: '',
text: ''
},
initialize: function() {
//alert(this.title);
}
});
var question2 = new Question;
var questionDetails = {title: 'test title', text: 'test text'};
question2.save(questionDetails, {
success: function(question) {
alert(question.toJSON());
}
});
Sounds like you need to pass the CSRF token through with your save request.
One solution would be to pass the CSRF token back to the model requesting it, then override your model's save method ensuring the model passes the CSRF token back with it.
The django docs have instructions on how to set up jquery to send the csrf token via ajax.
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
You should make sure that the template tag
{% csrf_token %}
renders something in your frontend. That way you know that the token is being created and passed to the frontend. If you follow the instructions from the docs above then your csrf token should always be sent with ajax requests. This is what the javascript looks like for one of my sites (assuming you are using jQuery).Also, make sure that
'django.middleware.csrf.CsrfViewMiddleware'
is in your MIDDLEWARE_CLASSES settings.