Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Rest Framework custom message for 404 errors

I have a generic class based view:

class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()
    # Rest of definition

And in my urls.py, I have:

urlpatterns = [
    url(r'^(?P<pk>[0-9]+)/$', views.ProjectDetails.as_view())
]

When the API is called with a non-existent id, it returns HTTP 404 response with the content:

{
    "detail": "Not found."
}

Is it possible to modify this response?

I need to customize error message for this view only.

like image 928
Arun Avatar asked Jul 14 '26 23:07

Arun


1 Answers

This solution affect all views:

Surely you can supply your custom exception handler: Custom exception handling

from rest_framework.views import exception_handler
from rest_framework import status

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response.status_code == status.HTTP_404_NOT_FOUND:
        response.data['custom_field'] = 'some_custom_value'

    return response

Sure you can skip default rest_framework.views.exception_handler and make it completely raw.

Note: remember to mention your handler in django.conf.settings.REST_FRAMEWORK['EXCEPTION_HANDLER']

Solution for specific view:

from rest_framework.response import Response
# rest of the imports

class ProjectDetails(mixins.RetrieveModelMixin,
                     mixins.UpdateModelMixin,
                     generics.GenericAPIView):
    queryset = Project.objects.all()

    def handle_exception(self, exc):
        if isinstance(exc, Http404):
            return Response({'data': 'your custom response'}, 
                            status=status.HTTP_404_NOT_FOUND)

        return super(ProjectDetails, self).handle_exception(exc)
like image 157
vishes_shell Avatar answered Jul 16 '26 11:07

vishes_shell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!