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?