I am trying to add some interactive things to the Django admin page through a simple RESTful api and Javascript. It should be simple, but I ran into a strange problem when each of my requests from javascript returns a 403 authorization error. Please note that this only applies to js. I can hit the url from the browser just fine and do all the basic CRUD stuff.
The code is very simple.
Javascript
$.ajax({ xhrFields: {withCredentials: true}, type: 'PATCH', url: 'path/to/my/endpoint, data: { aParam: someValue, 'csrfmiddlewaretoken': getCookie('csrftoken') }, success: doSomething, error: doSomething });
Python
class MyObjectDetail(RetrieveUpdateDestroyAPIView): queryset = MyObject.objects.all() serializer_class = MyObjectSerializer authentication_classes = (SessionAuthentication,) permission_classes = (IsAuthenticated,)
Initially, I suspected that the session identifier was not being sent, and thatβs why that's why everything failed due to permissions. However, the session cookie is indeed sent to the ajax POST and is selected by the Django middleware. Django does not start an admin session without problems. However (after a lot of debugging) I traced the rewriting of the user into the dispatch method in the Django Rest Framework - in particular, calling self.initialize_request . After this call returns, my Admin user is unloaded for one of the AnonymouseUser s rest frameworks.
I am completely lost. I spent about 2 hours with the debugger, but still do not understand why my user is replaced. Has anyone come across this before? Am I just doing something wrong?
source share