I found an even easier way to do this! It turns out that the base class Rest Framework GenericAPIView (from which all classes of the Generic View Framework Rest Framework are dropped) includes the get_serializer_context() function :
def get_serializer_context(self): """ Extra context provided to the serializer class. """ return { 'request': self.request, 'format': self.format_kwarg, 'view': self }
As you can see, the returned context object contains the same request object that the View receives. Then this object is set when the serializer is initialized :
def get_serializer(self, *args, **kwargs): """ Return the serializer instance that should be used for validating and deserializing input, and for serializing output. """ serializer_class = self.get_serializer_class() kwargs['context'] = self.get_serializer_context() return serializer_class(*args, **kwargs)
Thus, to access the user who executed the request, you just need to call self.context['request'].user from your Serializer validate_ function:
class TemplateSerializer(serializers.ModelSerializer): def validate_parent(self, value): print(self.context['request'].user) return value class Meta: model = Template
And most importantly, you donβt need to redefine anything in your ModelViewSet , they can remain as simple as you want:
class TemplateViewSet(viewsets.ModelViewSet): serializer_class = TemplateSerializer permission_classes = [IsAdmin]
source share