Skip to content
Advertisement

Django Rest Framework Database Error Exception Handling

Is there any way to have Django Rest Framework automatically respond with HTTP_400_STATUS‘s when there are database exceptions?

(IntegrityError and so on)

Example: I have a model with a unique username field and I’m trying to use a generic rest_framework.ListCreateAPIView. HTTP_400_STATUS‘s are normally thrown automatically if serializer validation fails but this is actually valid input, just not valid in the db. What should I do here?

Advertisement

Answer

You should extend ListCreateAPIView and catch the IntegrityError and handle it by returning a bad_request:

JavaScript

Interestingly you could raise a SuspiciousOperation instead of returning the bad_request explicitly:

JavaScript

Then django will return a 400 BAD REQUEST.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement