Django Rest Framework Database Error Exception Handling

Tags: , ,

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?


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

from django.views.defaults import bad_request
from rest_framework.generics import ListCreateAPIView

class MyListCreateAPIView(ListCreateAPIView):

    def create(self, request, *args, **kwargs):
            return super(ListCreateAPIView,self).create(request, *args, **kwargs)
        except IntegrityError:
            return bad_request(request)

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

        except IntegrityError:
            from django.core.exceptions import SuspiciousOperation
            raise SuspiciousOperation

Then django will return a 400 BAD REQUEST.

Source: stackoverflow