Home Ask Login Register

Developers Planet

Your answer is one click away!

parikLS February 2016

Django dont set CSRF token on AJAX GET from angularJS

I am writing application with AngularJS on frontend and Django as REST service on backend. I'm trying to send some JSON data using POST request, but facing with csrf-token issue (CSRF token missing or incorrect). As far as i know, previously i should make a GET request on Django to obtain this token. So i have wrote simple view:

def get_csrf_token(request):
    return HttpResponse(json.dumps({'success': True}))

I have added httpProvider defaults, and on start of angular application making GET request on view:

angular.module('app')
    .config(function($httpProvider){
        $httpProvider.defaults.xsrfCookieName = 'csrftoken';
        $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
    })
    .run(function($http){
        $http.get("http://127.0.0.1:8888/get_csrf_token/")
    })

but this view dont set a CSRF token, and i still cannot do POST request.

Answers


olofom February 2016

If your view is not rendering a template containing the csrf_token template tag, Django might not set the CSRF token cookie. This is common in cases where forms are dynamically added to the page. To address this case, Django provides a view decorator which forces setting of the cookie: ensure_csrf_cookie().

Post Status

Asked in February 2016
Viewed 1,788 times
Voted 5
Answered 1 times

Search




Leave an answer


Quote of the day: live life