0

There are loads of similar questions but each seems to deal with the problem under different scenarios, or the perscribed solution doesn't seem to resolve my issue. Basically, Why am I getting this 403 Forbidden Error?

POST http://127.0.0.1:8000/api/hello-viewset/ 403 (Forbidden)

The url is a Django Rest Framework (DRF) endpoint that I can access from the browser and make POSTs using the DRF gui just fine. The trouble is when I try to POST using Ajax from my javascript file. Note, that I am passing the CSRFToken (as advised here):

$.ajax({
    type: "POST",
    url: '/api/hello-viewset/',
    csrfmiddlewaretoken: window.CSRF_TOKEN, // yes, this variable is set successfully
    data: {first_name: username},
    success: function(data){
        console.log( 'success, server says '+data);
    }
});

The /api/hello-viewset/ url is just a simplified test view that looks like this:

class HelloViewSet(viewsets.ViewSet):

    serializer_class = serializers.HelloSerializer

    def post(self, request):
        serializer = serializers.HelloSerializer(data=request.data)

        if serializer.is_valid():
            first_name = serializer.data.get('first_name')
            message = 'Hello {0}'.format(first_name)
            return Response({'message': message})
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Thanks in advance for your help?

Michael Romrell
  • 1,026
  • 5
  • 15
  • 31

1 Answers1

2

csrfmiddlewaretoken: window.CSRF_TOKEN is not set correctly. It should be added to data, ie:

$.ajax({
    type: "POST",
    url: '/api/hello-viewset/',
    data: {
        first_name: username,
        csrfmiddlewaretoken: window.CSRF_TOKEN
    },
    success: function(data){
        console.log( 'success, server says '+data);
    }
});
BottleZero
  • 893
  • 6
  • 13