0

I'm currently working on a Django project and using Djoser for user authentication. where I need to access the request user within a serializer.


class TokenRefreshSerializer(serializers.Serializer):
    refresh = serializers.CharField()
    access = serializers.CharField(read_only=True)
    token_class = RefreshToken
    
    def validate(self, attrs: Dict[str, Any]) -> Dict[str, str]:
        refresh = self.token_class(attrs["refresh"])
        
        data = {"access": str(refresh.access_token)}

        if api_settings.ROTATE_REFRESH_TOKENS:
            if api_settings.BLACKLIST_AFTER_ROTATION:
                try:
                    # Attempt to blacklist the given refresh token
                    refresh.blacklist()
                except AttributeError:
                    # If blacklist app not installed, `blacklist` method will
                    # not be present
                    pass

            refresh.set_jti()
            refresh.set_exp()
            refresh.set_iat()

            # 1 option
            user_id = refresh['user_id']
            user = User.objects.get(id=user_id)

        return data

How can I access the request user here?

user = self.context['request'].user
            
print( user)

But i have AnonymousUser

1 Answer 1

0

The ViewSet using the serializer should have get_serializer_context method which can be used to provide the serializer with additional data

class MyViewSet(GenericViewSet):
    def get_serializer_context(self):
        context = super(MyViewSet, self).get_serializer_context()
        context.update({
            "request_user": self.request.user # or whatever field contains the current user
        })
        return context

Technically, you can put whatever you wish in the context (even the whole request) and pass it down to serializer, but I would advise you to use this carefully as it may overcomplicate things

Sign up to request clarification or add additional context in comments.

Comments

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.