I was creating a toggle button that triggers an HTTP request, a POST. I'm working with Angular on the front-end.
Problem
I'm trying to send form data via a POST request. My Django project uses the out-of-the-box CSRF security. There's a CSRF token stored in a cookie. That stored value (a token) is used to validate requests. How do send that CSRF token with my request via my Angular controller?
I'm creating a button for favoriting a post, by the way. Hence, the URL.
Solution
In your app config, tell Angular that with your HTTP request, you'll want to send over Django's custom HTTP header containing the CSRF token. The header attribute we're interested in is X-CSRF
.
var app = angular.module('feed', []);
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.xsrfCookieName = 'csrftoken';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);
Download jquery.cookie
Get the CSRF token from the cookie your Django application will have created upon loading your page (or upon the first GET).
app.controller("MyController", function($scope, $http) {
$scope.toggle_save = function(id) {
var fav_link = "story/" + id + "/favorite/";
var csrftoken = $.cookie('csrftoken'); //from jquery.cookie
$http.post(fav_link, {'csrfmiddlewaretoken': csrftoken }).
success(function(data, status, headers, config) {
alert('favorited');
// toggle stuff here.
}).
error(function(data, status, headers, config) {
alert(data);
});
}; // end toggle_save
});
The template looks like this:
<a href="#" class="post-links save-story" data-story-id="{{ story.id }}" ng-click="toggle_save(story.id)">Favorite</a>
Done.