I have a unique constraint on a database field. When a duplicate is submitted I'd like to avoid sending a 500 response. How can I catch this error in DRF and return a 4XX response instead?
I knew I needed to put a try/except block around something, but I didn't know what. I looked at the DRF code, and I saw that generics.ListCreateAPIView has a method called create. I wrote a new function inside my class called the parent create which has the same signature as the one I inherited, which called create, and I put the try/except around this function.
In the end it looks like this:
class MyModelList(generics.ListCreateAPIView):
def get_queryset(self):
return MyModel.objects.all()
def create(self, request, *args, **kwargs):
try:
return super(MyModelList, self).create(request, *args, **kwargs)
except IntegrityError:
raise CustomUniqueException
serializer_class = MyModelSerializer
I hope this helps someone.
If you want this only for this view override handle_exception
:
class MyAPIView(APIView):
...
def handle_exception(self, exc):
"""
Handle any exception that occurs, by returning an appropriate
response,or re-raising the error.
"""
...
To handle it for all views, you can define a global exception handler, see here: http://www.django-rest-framework.org/api-guide/exceptions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With