Answer the question
In order to leave comments, you need to log in
How to customize server errors (response's) in Django and Django Rest Framework?
I have a ViewSet:
...
from handlers import specific_exception_handler...
...
class SomeViewSet(GenericViewSet):
"""
Some custom generic viewset
"""
queryset = SomeModel.objects.all()
serializer_class = SomeSerializer
parser_classes = (ParserClassThatReadSpecificXML,)
renderer_classes = (RendererClassThatConvertResponseIntoSpecificXML,)
def get_exception_handler(self):
return specific_exception_handler_function_that_return_specific_xml_format_error
@action(methods=['post'], detail=False, url_path='some_url', url_name='some_url')
def register(self, request, format=None):
some_variable = request.data.get('some_value', None)
if not some_variable:
raise ValueError
return Response(data=some_variable, content_type="text/xml; charset=shift_jis")
...
import xmltodict
class RendererClassThatConvertResponseIntoSpecificXML(BaseRenderer):
media_type = 'text/xml'
format = 'txt'
charset = 'shift_jis'
def render(self, data, media_type=None, renderer_context=None):
# return data as non utf-8 xml string
return xmltodict.unparse(data).encode("shift_jis")
...
from rest_framework.views import exception_handler
def specific_exception_handler_function_that_return_specific_xml_format_error(exc, context):
response = exception_handler(exc, context)
if response is not None:
status_code = response.status_code
else:
status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
specific_data_that_will_be_converted_into_xml_by_render = {'ERROR_STATUS': status_code}
headers = {'Retry-After': '300'}
return Response(data, content_type='text/xml; charset=shift_jis', status=status_code, headers=headers)
Answer the question
In order to leave comments, you need to log in
500 status is when you can no longer do anything with an error and that means your XML will always be the same for such an error, just create a 500.html file with this xml and put it in the template path, with 404 the same way. But keep in mind that in DEBUG = True, they are not returned. https://docs.djangoproject.com/en/3.0/ref/views/#e... Well, or through overriding https://docs.djangoproject.com/en/dev/topics/http/...
PS on The DRF level also has its own views https://www.django-rest-framework.org/api-guide/ex...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question