Search code examples
django-rest-frameworkhttp-status-codesserialization

Django REST Framework ValidationError always returns 400


I am trying to force ValidationError to return a different status code than 400. This is what I did:

class MyValidationError(ValidationError):
    status_code = HTTP_403_FORBIDDEN

and then in a serializer:

def validate_field(self, value):
    raise MyValidationError

Why do I get 400 here instead of 403? An interesting thing is that if I use PermissionDenied with a custom status code (I tried 204) instead of ValidationError, it works as expected.


Solution

  • The Django RestFramework serializer validates all possible fields and finally returns set of errors.

    That is, suppose you are expecting two validation errors in serializer, in that one validation error is raised by MyValidationError. In that case DRF obviously return HTTP 400 status code, because the design patterns of DRF not raising individual validation errors.

    The serializer validation process done inside the is_valid() method and it raises ValidationError at the end of the method.

    def is_valid(self, raise_exception=False):
        ....code
        ....code
        if self._errors and raise_exception:
            raise ValidationError(self.errors)
    
        return not bool(self._errors)

    and the ValidationError class raises HTTP 400

    class ValidationError(APIException):
        status_code = status.HTTP_400_BAD_REQUEST
        default_detail = _('Invalid input.')
        default_code = 'invalid'
        .... code


    Why PermissionDenaid returns custom status code?

    In the is_valid() (source code) method, it catches only ValidationError

    if not hasattr(self, '_validated_data'):
        try:
            self._validated_data = self.run_validation(self.initial_data)
        except ValidationError as exc:
            self._validated_data = {}
            self._errors = exc.detail
        else:
            self._errors = {}
    At that time, DRF directly raises a PermissionDenaid exception and returns its own status code, which is customized by you


    Conclusion

    DRF Serializer ValidationError never returns status code other that HTTP 400 because it catches other sub validation error exceptions(if any) and atlast raises a major ValidationError which return HTTP 400 status code by it's design pattern

    Reference:
    is_valid() source code
    ValidationError class source code