Last Updated: September 09, 2019
·
927
· imran-aspire

Django CSRF Token issue in Angularjs

  • First add django tag {% csrf_token %} in the markup.
  • Add a $http inspector in your app config file
    angular.module('myApp').config(function ( $httpProvider) {
    $httpProvider.interceptors.push('myHttpRequestInterceptor'); });
    </code>

  • Then define that myHttpRequestInterceptor
    angular.module("myApp").factory('myHttpRequestInterceptor', function ( ) { return { config.headers = { 'X-CSRFToken': $('input[name=csrfmiddlewaretoken]').val() } } return config; } }; });

</code>

it'll add the X-CSRFToken in all angular request

  • And lastly you need to add the Django middleware " django.middleware.csrf.CsrfViewMiddleware'"

It'll solve the CSRF issue