序列化器 ValidationError 的自定义格式
我在我的序列化器之一中有一个自定义对象级验证器:
def validate(self, data):
# some checks on token
# set token to True or False
if not token:
raise serializers.ValidationError(
{
"status": "failed",
"message": _("token is not valid"),
}
)
return data
我期望得到的输出是这样的:
{
"status": "failed",
"message": "token is not valid"
}
但是,我实际得到的是:
{
"status": [
"failed"
],
"message": [
"token is not valid"
]
}
有没有办法实现我正在寻找的东西?
Iv'e got a custom object-level validator in one of my serializers:
def validate(self, data):
# some checks on token
# set token to True or False
if not token:
raise serializers.ValidationError(
{
"status": "failed",
"message": _("token is not valid"),
}
)
return data
What I expect to get as an output is this:
{
"status": "failed",
"message": "token is not valid"
}
However, what I'm actually getting is:
{
"status": [
"failed"
],
"message": [
"token is not valid"
]
}
Is there anyway to achieve what I'm looking for?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
创建自定义
ValidatorError
类:不要使用
serializers.ValidationError
,而是使用自定义ValidationError
类:它并不完美,但它适合我。
Create a custom
ValidatorError
class:Instead of using
serializers.ValidationError
use your customValidationError
class:It's not perfect but it does the job for me.
通过在视图端验证您的令牌,您可以更轻松地实现此目的。例如,您的视图将如下所示:
您可以设置该行
如果您还有其他验证要做,请将
serializer.is_valid()
更改为serializer.is_valid(raise_exception=True)
。我希望这会有所帮助
It will be easier for you to achieve this by validating your token at the view side instead. For example your view will look like this:
You can set the line
serializer.is_valid()
toserializer.is_valid(raise_exception=True)
if you have other validations to do.I hope this will help