Pass request context to serializer from Viewset in Django Rest Framework
GenericViewSet
has the get_serializer_context
method which will let you update context
:
class myModelViewSet(ModelViewSet):
queryset = myModel.objects.all()
permission_classes = [DjangoModelPermissions]
serializer_class = myModelSerializer
def get_serializer_context(self):
context = super(myModelViewSet, self).get_serializer_context()
context.update({"request": self.request})
return context
just use get_serializer() in your viewsets
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)
For Function based views you can pass request or user as follow:
serializer = ProductSerializer(context = {'request':request},data=request.data)
Your Serializer may look like:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ['id']
def create(self, validated_data):
user = self.context['request'].user
print("User is")
print(user)
Feel free to inform if there is any better way to do this.