2

I have implemented my custom Renderer like this:

from rest_framework.renderers import JSONRenderer

class CustomJSONRenderer(JSONRenderer):

def render(self, data, accepted_media_type=None, renderer_context=None):

    //I am hardcoding status and message for now. Which I have to update according to the response.
    data = {'data': data, 'message':'ok', 'status':200 }

    return super(CustomJSONRenderer, self).render(data, accepted_media_type, renderer_context)

This is working pretty good. Now I want to update status using HTTP status code of response and thus providing a custom message. So how should I achieve this?

Basically I want the response like this:

{"status":200, "data":[actual data comes here.], "message":"ok"}

1
  • What is the type of data? Commented Feb 19, 2016 at 10:19

2 Answers 2

3

Well on a different note I found out that we can get the status information. The renderer_context parameter actually contains the following information-

{'view': <ViewSet object at 0x7ff3dcc3fac0>, 'args': (), 'kwargs': {}, 'request': <rest_framework.request.Request object at 0x7ff3dcc37e20>, 'response': <Response status_code=400, "application/json; charset=utf-8">}

This means the renderer_context parameter is a dictionary and can be exploited in order to modify your response. For example -

    def render(self, data, accepted_media_type=None, renderer_context=None):
        if renderer_context is not None:
            print(renderer_context['response'].status_code)
Sign up to request clarification or add additional context in comments.

Comments

2

This is not what renderers are made for. You should use a renderer to transform the response into a certain format (json, html, csv, etc) according to the request. By default it will use the Acceptheader, but you could image to pass a querystring parameter to force a different output.

I think what you are trying to do is a custom error exception http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

Hope this helps

Comments

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.