[Answered ]-Accessing user in django rest framework

2👍

You get it from the context that was passed to the serializer. This is done automatically for you, so you can access it like that:

user = self.context['request'].user

If you want to have the ability to specify another user, you can add it to the context yourself:

# This method goes in your view/viewset
def get_serializer_context(self):
    context = super().get_serializer_context()
    context['user'] = #whatever you want here
    return context

That would make the user available as self.context['user']. This is a bit more verbose, but it is more versalite as it allows the serializer to be passed a user different from the one who did the request.

Leave a comment