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().get_serializer_context()
        context.update({"request": self.request})
        return context

For Python 2.7, use context = super(MyModelViewSet, self).get_serializer_context()

Leave a Comment