arooo arooo - 1 year ago 241
Python Question

Django Rest Framework Database Error Exception Handling

Is there any way to have Django Rest Framework automatically respond with

's when there are database exceptions?

and so on)

Example: I have a model with a unique username field and I'm trying to use a generic
'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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download