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
x
11
11
1
from django.views.defaults import bad_request
2
from rest_framework.generics import ListCreateAPIView
3
4
class MyListCreateAPIView(ListCreateAPIView):
5
6
def create(self, request, *args, **kwargs):
7
try:
8
return super(ListCreateAPIView,self).create(request, *args, **kwargs)
9
except IntegrityError:
10
return bad_request(request)
11
Interestingly you could raise a SuspiciousOperation
instead of returning the bad_request explicitly:
JavaScript
1
4
1
except IntegrityError:
2
from django.core.exceptions import SuspiciousOperation
3
raise SuspiciousOperation
4
Then django will return a 400 BAD REQUEST
.