0

I'm using ModelViewSet and struggling to setup a rendering standard. The documentation doesn't show how to use ModelViewSet with drf renderers. I want the output to be of this format:

Format : {'message': <custom message>, 'data': <output from ModelViewSet>}

Code:

class PostViewSet(viewsets.ModelViewSet):
    serializer_class = PostSerializer
    queryset = Post.objects.all()
    permission_classes = [permissions.IsAuthenticated]
    renderer_classes = [GenericAPIRenderer]

# How to Override?
class GenericAPIRenderer(renderers.JSONRenderer):
    charset = 'utf-8'

    def render(self, data, media_type=None, renderer_context=None):
        pass

1 Answer 1

1

Something like this works without any issue,

class GenericAPIRenderer(renderers.JSONRenderer):
    charset = 'utf-8'

    def render(self, data, accepted_media_type=None, renderer_context=None):
        updated_data = {'message': "some custom message", 'data': data}
        return super().render(updated_data, accepted_media_type, renderer_context)
Sign up to request clarification or add additional context in comments.

6 Comments

How do I pass on a custom message from the view layer?
if you want to inject the "custom message* from view, then, better override the corresponding methods
@AshfaqUrRahmanN renderer_context seems to be the appropriate place to pass additional information, or add your own parameter
@ArakkalAbu According to the docs for renderer_context: "By default this will include the following keys: view, request, response, args, kwargs.". Seems like it should contain the required data. django-rest-framework.org/api-guide/renderers/…
I wasn't aware of that point, thanks for the info @IainShelvington
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.