DRF: Get request object in custom renderer

733 views Asked by At

I'm building a serverside using django==1.10 and djangorestframework==3.4.6

I have build a JSONRenderer:

class CustomJSONRenderer(JSONRenderer):
     def render(self, data, accepted_media_type=None, renderer_context=None):
        meta_fields = ["temp_save", "subject", "visit"]
        a = {"fields": {}}
        for k in data:
            try:
                meta_fields.index(k)  # Crashes with ValueError if not found
                a[k] = data[k]
            except ValueError:
                a["fields"][k] = data[k]
        return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)

Question: Is it possible to get the views request object? I specifically want to access the urls parameters (e.g request.kwargs['pk']

1

There are 1 answers

2
Devansh On BEST ANSWER

You can get request from renderer_context as following.

request = renderer_context['request']

Your Code:

class CustomJSONRenderer(JSONRenderer):
     def render(self, data, accepted_media_type=None, renderer_context=None):
        request = renderer_context['request'] or None
        meta_fields = ["temp_save", "subject", "visit"]
        a = {"fields": {}}
        for k in data:
            try:
                meta_fields.index(k)  # Crashes with ValueError if not found
                a[k] = data[k]
            except ValueError:
                a["fields"][k] = data[k]
        return super(CustomJSONRenderer, self).render(a, accepted_media_type, renderer_context)

May be this will help you.