zoukankan      html  css  js  c++  java
  • Django 自定义 error_messages={} 返回错误信息

    Considerations regarding model’s error_messages

    Error messages defined at the form field level or at the form Meta level always take precedence over the error messages defined at the model field level.

    Error messages defined on model fields are only used when the ValidationError is raised during the model validation step and no corresponding error messages are defined at the form level.

    # 您可以通过将NON_FIELD_ERRORS键添加到ModelForm的内部Meta类的error_messages字典中来覆盖模型验证所引起的NON_FIELD_ERRORS错误消息:

    You can override the error messages from NON_FIELD_ERRORS raised by model validation by adding the NON_FIELD_ERRORS key to the error_messages dictionary of the ModelForm’s inner Meta class:

    from django.core.exceptions import NON_FIELD_ERRORS
    from django.forms import ModelForm
    
    class ArticleForm(ModelForm):
        class Meta:
            error_messages = {
                NON_FIELD_ERRORS: {
                    'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
                }
            }




    对于常见序列化error_message可以使用以下:

    例子IntegerField

    class ShopCartSerializer(serializers.Serializer):

    nums = serializers.IntegerField(required=True,label='数量',min_value=1,error_messages={

    "min_value":"商品数量不能小于一","required":"请选择购物数量"})
     

    不同类型的字段有不同的 error_messages 定义

    查看rest framework 源码 看到最基础的field  中定义了两个error_messages

    class Field(object):
    _creation_counter = 0

    default_error_messages = {
    'required': _('This field is required.'),
    'null': _('This field may not be null.')
    }
    不同字段中还定义了不同的error_messages   IntegerField 中增加了

    class IntegerField(Field):
    default_error_messages = {
    'invalid': _('A valid integer is required.'),
    'max_value': _('Ensure this value is less than or equal to {max_value}.'),
    'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
    'max_string_length': _('String value too large.')
    }
    这里面的字段我们可以自定义返回前端

     CharField

    class CharField(Field):
    default_error_messages = {
    'invalid': _('Not a valid string.'),
    'blank': _('This field may not be blank.'),
    'max_length': _('Ensure this field has no more than {max_length} characters.'),
    'min_length': _('Ensure this field has at least {min_length} characters.')
    }
    例子:

    code = serializers.CharField(required=True, write_only=True, max_length=6, min_length=6,
    error_messages={
    "blank": "请输入验证码",
    "required": "请输入验证码",
    "max_length": "验证码格式错误",
    "min_length": "验证码格式错误"
    },
    help_text="验证码")
     

    外键字段

    class PrimaryKeyRelatedField(RelatedField):
    default_error_messages = {
    'required': _('This field is required.'),
    'does_not_exist': _('Invalid pk "{pk_value}" - object does not exist.'),
    'incorrect_type': _('Incorrect type. Expected pk value, received {data_type}.'),
    }

    当然也可以使用validator:

    project_name = serializers.CharField(max_length=50, required=True,
    validators=[UniqueValidator(queryset=models.ProjectInformation.objects.all())]
    )

    还可以再extra_kwargs里使用:

    class Meta:
    model = models.JenkinsServices
    fields = "__all__"
    validators = [
    UniqueTogetherValidator(
    queryset=models.JenkinsServices.objects.all(),
    fields=['project_id', 'service_name']
    )
    ]
    extra_kwargs = {"service_name": {"error_messages": {"required": "Give your service_name"}}}

    其次模型层也可以限制:
    from django.core.validators import (MaxValueValidator, MinValueValidator,
    MinLengthValidator,MaxLengthValidator)
     
    class JenkinsServices(models.Model):
    project_id = models.IntegerField(
    validators=[MaxValueValidator(1000), MinValueValidator(1)])
    service_name = models.CharField(max_length=100, null=False)
     
  • 相关阅读:
    mysql 分列或取子串
    Excel “20200504”文本格式转化为时间格式
    Mysql清空数据表
    python 做词云图
    Pandas操作excel
    python中zip()函数的用法
    Excel技能提升
    JS 学习笔记
    元类理解与元类编程 《Python3网络爬虫开发》中第九章代理的使用代码Crawler中代码的理解
    关于选择器注意的点
  • 原文地址:https://www.cnblogs.com/SunshineKimi/p/13886429.html
Copyright © 2011-2022 走看看