Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework: Passing Context in Viewsets

Viewsets are convenient because we can do stuff like this and get a fully working serializer:

class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]
    queryset = StoreObject.active_objects.all()
    serializer_class = serializers.StoreObjectSerializer

Unfortunately, as far as I know– to pass the context into the serializer we need to do things like this:

PostSerializer(data=request.data, context={'request': request})

Which means we need to manually override every convenient method provided by ViewSets (as far as I know). Is there a way to inject the context into every serializer while still keeping Viewsets convenient?

like image 851
aroooo Avatar asked Jun 12 '26 21:06

aroooo


1 Answers

By default, request is being sent to any Generic View and ViewSet. You can check the source code in GitHub as well. So you do not have to inject them in every view. If you want to pass extra context, then override get_serializer_context(...) method:

class StoreObjectViewSet(mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    ...

    def get_serializer_context(self):
        context = super().get_serializer_context()
        context['custom_context'] = 'Your custom context'
        return context
like image 127
ruddra Avatar answered Jun 15 '26 11:06

ruddra



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!