[Answered ]-Django Rest Framework is throwing 400 before I can handle exception for ModelViewSet

1👍

You need to capture a ValidationError exception instead. The reason behind this is because you’ve defined your email field unique=True and Django will automatically check that when you call serializer.is_valid().

In addition, you can check for unique constraint error by using exc. get_full_details()

try:
    serializer.is_valid(raise_exception=True)
except ValidationError as exc:
    errors = exc.get_full_details()
    if 'email' in errors and errors['email']['code'] == 'unique':
        # do something, maybe re-raise with your custom exception:
        raise EmailExists from exc

Ref

Leave a comment