Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

367
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda