Django and Middleware which uses request.user is always Anonymous

前端 未结 7 1366
天命终不由人
天命终不由人 2021-01-30 10:37

I\'m trying to make middleware which alters some fields for the user based on subdomain, etc...

The only problem is the request.user always comes in as AnonymousUser wit

7条回答
  •  逝去的感伤
    2021-01-30 11:36

    I know it's not exactly answering the 'can we access that from the middleware' question, but I think it's a more elegant solution VS doing the same work in the middleware VS what DRJ does in its base view class. At least for what I needed, it made more sense to add here.

    Basically, I'm just overriding the method 'perform_authentication()' from DRF's code, since I needed to add more things related to the current user in the request. The method just originally call 'request.user'.

    class MyGenericViewset(viewsets.GenericViewSet):
    
        def perform_authentication(self, request):
            request.user
    
            if request.user and request.user.is_authenticated():
                request.my_param1 = 'whatever'
    

    After that in your own views, instead of settings APIView from DRF as a parent class, simply set that class as a parent.

提交回复
热议问题