How to disable HTML error page return with the django framework?

advertisements

If I have a error outside the libs of DRF, django send back the HTML of the error instead of the proper error response use by DRF.

For example:

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    print request.POST['tables']

Return the exception MultiValueDictKeyError: "'tables'". And get back the full HTML. How get only the error a JSON?

P.D:

This is the final code:

@api_view(['GET', 'POST'])
def process_exception(request, exception):
    # response = json.dumps({'status': status.HTTP_500_INTERNAL_SERVER_ERROR,
    #                        'message': str(exception)})
    # return HttpResponse(response,
    #                     content_type='application/json; charset=utf-8')
    return Response({
        'error': True,
        'content': unicode(exception)},
        status=status.HTTP_500_INTERNAL_SERVER_ERROR
    )

class ExceptionMiddleware(object):
    def process_exception(self, request, exception):
        # response = json.dumps({'status': status.HTTP_500_INTERNAL_SERVER_ERROR,
        #                        'message': str(exception)})
        # return HttpResponse(response,
        #                     content_type='application/json; charset=utf-8')
        print exception
        return process_exception(request, exception)


One way of returning json would be to catch the exceptions and return proper response (assuming you're using JSONParser as default parser):

from rest_framework.response import Response
from rest_framework import status

@api_view(['POST'])
@permission_classes((IsAuthenticated,))
def downloadData(request):
    try:
        print request.POST['tables']
    except:
        return Response({'error': True, 'content': 'Exception!'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    return Response({'error': False})

UPDATE

For global wise use-case the correct idea would be to put the json response in exception middleware.

You can find example in this blog post.

In your case you need to return DRF response, so if any exception gets raised it will end up in the process_exception:

from rest_framework.response import Response

class ExceptionMiddleware(object):

    def process_exception(self, request, exception):
        return Response({'error': True, 'content': exception}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)