首页 > 其他 > 详细

django serializer 定制error_message

时间:2019-02-25 19:00:34      阅读:232      评论:0      收藏:0      [点我收藏+]

1,在字段上定制字段信息的判断

class CreateManagerSerializers(serializers.ModelSerializer):
    username = serializers.CharField(validators=[UniqueValidator(
        queryset=models.Manager.objects.all(),
        message=名称重复
    )])
    password = serializers.CharField(write_only=True)

==>在传入库里面已经有的名字时,显示错误信息

{
"username": [
"名称重复"
]
}

2,在Meta中定制错误信息,效果和字段上定制一样


class Meta:
model = models.Manager
fields = [‘username‘, ‘password‘, ‘email‘, ‘mobile_number‘, ‘role_num‘, ‘channel‘]
extra_kwargs = {
‘username‘:{‘validators‘:[UniqueValidator(
queryset=models.Manager.objects.all(),
message=‘名称重复‘)]},
‘email‘: {‘validators‘: [UniqueValidator(
queryset=models.Manager.objects.all(),
message=‘email重复‘)]},
}


==>错误信息和上面一样

{
"username": [
"名称重复"
],
"email": [
"email重复"
]
}

3,利用valition_字段 raise报错信息

class CreateManagerSerializers(serializers.ModelSerializer):
    username = serializers.CharField()
    password = serializers.CharField(write_only=True)    
    def validate_username(self,value):
        from rest_framework.exceptions import ValidationError
        flag=models.Manager.objects.filter(username=value).exists()
        if flag:
            raise ValidationError(用户名称重复)
        return value

==>报错信息

{
"username": [
"用户名称重复"
],
"email": [
"email重复"
]
}

 

django serializer 定制error_message

原文:https://www.cnblogs.com/52forjie/p/10432538.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!