Demetris Demetris - 5 months ago 25
Python Question

Customize NotFound exception --- Django REST Framework

Assume a minimal application with a

model, a
and a corresponding

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

"name": "RandomName1"

When requesting
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
should return:

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

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['status_code'] == 404:
  ['detail'] = "{name} {id} was not found.".format(
                id=context['kwargs']['id']  # this may need tweaking
        except AttributeError:

    return response

Then add the corresponding verbose_name to your view.