1

I'm new to both Django and AngularJS and I've been struggling on this for hours.

AngularJS Code (of my controller) to POST to Django Server:

$http({
    method: 'POST',
    url: 'http://127.0.0.1:8000/polls/', // This is the Django server IP
    data: {'string': 'body'}
    }).then(function successCallback(response) {
     $scope.var= "success";
  }, function errorCallback(response) {
    $scope.var= response; // To display error. 
     });

    }
})

Django Server Code (in view):

def index(request):
    return "true"

The exact error that I'm getting is: POST http://127.0.0.1:8000/polls/ 403 (Forbidden)

Details of error- CSRF verification failed. Request aborted.You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. Blah blah.

EDIT Would prefer solutions that would work without affecting any of the security provisions of Django

2 Answers 2

2

You must include the token csrf in the header of the post call

    var csrf ='{{ csrf_token }}';
    $http({
        method: 'POST',
        headers: {'X-CSRFToken' : csrf },
        url: 'http://127.0.0.1:8000/polls/', // This is the Django server IP
        data: {'string': 'body'}
        }).then(function successCallback(response) {
         $scope.var= "success";
      }, function errorCallback(response) {
        $scope.var= response; // To display error. 
         });

        }
    })

or excempt csrf token for this call

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def index(request):
    return "true"
Sign up to request clarification or add additional context in comments.

Comments

0

If you have activate cors headers.

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def index(request):
    return "true"

2 Comments

Yes I've activated cords headers. But isn't there a way to do it without csrf_exempt, since I would like to keep it secure.
Also even when I try csrf_exempt, it leads to an internal server error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.