问题描述
我正试图强制 ValidationError
返回不同于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
然后在序列化器中:
def validate_field(self, value):
raise MyValidationError
为什么我在这里得到400而不是403?有趣的是,如果我使用带有自定义状态代码的 PermissionDenied
(我尝试过204)而不是 ValidationError
,它将
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.
推荐答案
Django RestFramework序列化程序将验证所有可能的字段并最终返回错误集 。
也就是说,假设您在序列化程序中遇到两个验证错误,因为 MyValidationError
会引发一个验证错误。在那种情况下,DRF显然会返回 HTTP 400
状态代码,因为DRF的设计模式不会引发个人验证错误。
在方法,并在方法末尾引发ValidationError。
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)
和类引发 HTTP 400
class ValidationError(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = _('Invalid input.')
default_code = 'invalid'
.... code
为什么PermissionDenaid返回自定义状态代码?
在方法,仅捕获 ValidationError
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 = {}
那时,DRF直接引发 PermissionDenaid
异常并返回由您自定义的状态代码
At that time, DRF directly raises a PermissionDenaid
exception and returns its own status code, which is customized by you
DRF序列化程序ValidationError 从不返回状态c以及 HTTP 400
的其他原因,因为它捕获了其他子验证错误异常 (如果有)并最终引发了主要的 ValidationError
通过其设计模式返回 HTTP 400
状态码
参考:
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 codeValidationError
class source code
这篇关于Django REST框架ValidationError总是返回400的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!