Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

366
Views
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."
}
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!