Demetris Demetris - 7 months ago 33
Python Question

Customize NotFound exception --- Django REST Framework

Assume a minimal application with a

person
model, a
ModelSerializer
and a corresponding
ReadOnlyModelViewSet
.

Only one entry exists in the database so when requesting
/person/1
the response correctly is:

{
"name": "RandomName1"
}


When requesting
/person/2
the response is:

{
"detail": "Not found."
}


I want to customize this.

Even though I read the documentation it is not clear how I can customize this.

I should clarify that I am looking to customize this, according to the view. For example
/person/2
should return:

{
"detail": "Person 2 was not found."
}


and
/address/3
should return:

{
"detail": "Address 3 was not found."
}

Answer Source

It sounds like you want to handle responses which have a 404 status code. Modifying the example from the linked documentation:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)

    if response.data['status_code'] == 404:
        try:
            response.data['detail'] = "{name} {id} was not found.".format(
                name=context['view'].verbose_name,
                id=context['kwargs']['id']  # this may need tweaking
            )
        except AttributeError:
            pass

    return response

Then add the corresponding verbose_name to your view.