In my project I use DRF as backend and Angular as frontend.
Django==1.10 djangorestframework==3.7.1
I need all responses from DRF to be in the following format.
This would be more a more robust solution, as it can be used with Generic Views hassle free.
Also, the checks in render() can be easily altered as per the needs (Eg., handling no-2XX in this solution).
from rest_framework.renderers import JSONRenderer
class CustomRenderer(JSONRenderer):
def render(self, data, accepted_media_type=None, renderer_context=None):
status_code = renderer_context['response'].status_code
response = {
"status": "success",
"code": status_code,
"data": data,
"message": None
}
if not str(status_code).startswith('2'):
response["status"] = "error"
response["data"] = None
try:
response["message"] = data["detail"]
except KeyError:
response["data"] = data
return super(CustomRenderer, self).render(response, accepted_media_type, renderer_context)