I think that this not depend of my serializer. I only want that the response data will be inside data variable in the JSON response and i need to add status variable and message to the JSON response. I can to rewrite all Class Based Views of DRF to response with my desired format. but this sound not very good.
I can do this:
def post(self, request, *args, **kwargs):
...........blah...blah
...........return Response({ 'status': true, 'message': 'login success', 'data': {'token':'345rjgjfegjgdsaj,fdgjsafgj'}})
right?
but this required rewrite all DRF methods on Class Based Views to change the response format.
I'm trying to use Renderers. I think that is the best for this. But I'm not sure how to pass message from views to renderers. it returns me to the same problem.
But this required pass from every view message attribute to data (since all messages depend on the view) example:
{ status: True, message:"user regitered", data: {user: {user detail...., token...}}} (Register View) --> has custom message
{ status: True, message:"logout successfully", data: {} (Logout View) --> has custom message
from rest_framework import status
from rest_framework.renderers import JSONRenderer
class GlobalJSONRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
this function change the response format to return the follow
format:
{
'status': True o False, -> Depend of status code
'message': '', -> A message (not yet)
'data': {} -> All Data
}
"""
data = {
'status': False,
'message': '',
'data': data
}
response = renderer_context['response']
status_code = response.status_code
if status.is_success(status_code):
data['status'] = True
return super(GlobalJSONRenderer, self).render(
data,
accepted_media_type,
renderer_context
)