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.
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 returnHTTP 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.and the
ValidationError
class raisesHTTP 400
Why PermissionDenaid returns custom status code?
In the
At that time, DRF directly raises ais_valid()
(source code) method, it catches onlyValidationError
PermissionDenaid
exception and returns its own status code, which is customized by youConclusion
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 majorValidationError
which returnHTTP 400
status code by it's design patternReference:
is_valid()
source codeValidationError
class source code