验证器¶
编写验证器¶
A validator is a callable that takes a value and raises a
ValidationError if it doesn't meet some
criteria. Validators can be useful for reusing validation logic between
different types of fields.
例如,这里有一个只允许偶数的验证器:
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
def validate_even(value):
if value % 2 != 0:
raise ValidationError(
_('%(value)s is not an even number'),
params={'value': value},
)
你可以通过字段的 validators 参数将其添加到模型字段:
from django.db import models
class MyModel(models.Model):
even_field = models.IntegerField(validators=[validate_even])
因为在验证器运行之前,值已经被转换为 Python,你甚至可以在表单中使用相同的验证器:
from django import forms
class MyForm(forms.Form):
even_field = forms.IntegerField(validators=[validate_even])
你也可以使用一个带有 __call__() 方法的类,用于更复杂或可配置的验证器。 RegexValidator,例如,使用了这种技术。如果在 validators 模型字段选项中使用了一个基于类的验证器,你应该通过添加 deconstruct() 和 __eq__() 方法来确保它是 可由迁移框架序列化。
如何运行验证器¶
请参阅 表单验证器 了解更多关于表单中如何运行验证器的信息,以及 验证对象 了解模型中如何运行验证器。请注意,当你保存模型时,验证器不会自动运行,但如果你使用的是 ModelForm,它将在你的表单中包含的任何字段上运行验证器。请参阅 模型表单文档,了解模型验证如何与表单交互。
内置验证器¶
django.core.validators 模块包含了一系列用于模型和表单字段的可调用验证器。它们是内部使用的,但也可以用于你自己的字段。它们可以作为自定义 field.clean() 方法的补充,也可以代替这些方法。
RegexValidator¶
-
class
RegexValidator(regex=None, message=None, code=None, inverse_match=None, flags=0)[源代码]¶ 参数: 一个
RegexValidator用re.search()为给定的正则表达式搜索提供的value。默认情况下,如果没有 找到 匹配的,会引发一个ValidationError,包含message和code。它的行为可以通过将inverse_match设置为True来反转,在这种情况下,当 找到 匹配的时,就会引发ValidationError。-
regex¶ 使用
re.search()在提供的value中搜索的正则表达式模式。可以是一个字符串,也可以是用re.compile()创建的预先编译的正则表达式。默认为空字符串,将在所有可能的value中找到。
-
message¶ 当验证失败时
ValidationError使用的错误信息。默认值为"Enter a valid value"。
-
code¶ ValidationError验证失败时使用的错误代码。默认值为"invalid"。
-
EmailValidator¶
-
class
EmailValidator(message=None, code=None, allowlist=None)[源代码]¶ 参数: -
message¶ 如果验证失败,
ValidationError使用的错误信息。默认为"Enter a valid email address"。
-
code¶ ValidationError验证失败时使用的错误代码。默认值为"invalid"。
-
allowlist¶ Allowlist of email domains. By default, a regular expression (the
domain_regexattribute) is used to validate whatever appears after the@sign. However, if that string appears in theallowlist, this validation is bypassed. If not provided, the defaultallowlistis['localhost']. Other domains that don't contain a dot won't pass validation, so you'd need to add them to theallowlistas necessary.
-
URLValidator¶
-
class
URLValidator(schemes=None, regex=None, message=None, code=None)[源代码]¶ RegexValidator子类,确保一个值看起来像一个 URL,如果不像,则引发'invalid'的错误代码。回环地址和保留的 IP 空间被认为是有效的。字面 IPv6 地址(RFC 3986#section-3.2.2)和 Unicode 域都支持。
除了它的父类
RegexValidator的可选参数外,URLValidator还接受一个额外的可选属性:
validate_email¶
-
validate_email¶ 一个
EmailValidator实例,没有任何自定义。
validate_slug¶
-
validate_slug¶ 一个
RegexValidator实例,确保一个值只由字母、数字、下划线或连字符组成。
validate_unicode_slug¶
-
validate_unicode_slug¶ 一个
RegexValidator实例,确保一个值只由 Unicode 字母、数字、下划线或连字符组成。
validate_ipv4_address¶
-
validate_ipv4_address[源代码]¶ 一个
RegexValidator实例,确保一个值看起来像一个 IPv4 地址。
validate_ipv46_address¶
validate_comma_separated_integer_list¶
-
validate_comma_separated_integer_list¶ 一个
RegexValidator实例,确保一个值是一个逗号分隔的整数列表。
int_list_validator¶
-
int_list_validator(sep=',', message=None, code='invalid', allow_negative=False)[源代码]¶ 返回一个
RegexValidator实例,以确保字符串由sep分隔的整数组成。当allow_negative为True时,它允许负整数。
MaxValueValidator¶
-
class
MaxValueValidator(limit_value, message=None)[源代码]¶ 如果
value大于limit_value,会引发一个ValidationError,代码为'max_value',这可能是一个可调用对象。
MinValueValidator¶
-
class
MinValueValidator(limit_value, message=None)[源代码]¶ 如果
value小于limit_value,会引发一个ValidationError,代码为'min_value',这可能是一个可调用对象。
MaxLengthValidator¶
-
class
MaxLengthValidator(limit_value, message=None)[源代码]¶ 如果
value的长度大于limit_value,会引发一个ValidationError,代码为'max_length'。
MinLengthValidator¶
-
class
MinLengthValidator(limit_value, message=None)[源代码]¶ 如果
value小于limit_value,会引发一个ValidationError,代码为'min_length',这可能是一个可调用对象。
DecimalValidator¶
-
class
DecimalValidator(max_digits, decimal_places)[源代码]¶ 引发
ValidationError,代码如下:'max_digits',如果数字数量大于max_digits。'max_decimal_places',如果小数的数量大于decimal_places。'max_whole_digits',如果整数位数大于max_digits和decimal_places之间的差值。
FileExtensionValidator¶
-
class
FileExtensionValidator(allowed_extensions, message, code)[源代码]¶ 如果
value.name(value是一个File`)的扩展名没有在allowed_extensions中找到,会引发一个ValidationError,代码为'invalid_extension'。该扩展名将与allowed_extensions进行不区分大小写的比较。警告
不要依赖文件扩展名的验证来确定文件的类型。文件可以重命名为任何扩展名,无论它们包含什么数据。
validate_image_file_extension¶
-
validate_image_file_extension[源代码]¶ 使用 Pillow 确保
value.name(value是一个File)具有 一个有效的图像扩展名 。
ProhibitNullCharactersValidator¶
-
class
ProhibitNullCharactersValidator(message=None, code=None)[源代码]¶ Raises a
ValidationErrorifstr(value)contains one or more null characters ('\x00').参数: -
message¶ 如果验证失败,
ValidationError使用的错误信息。默认值为"Null characters are not allowed."。
-
code¶ 当验证失败时
ValidationError所使用的错误代码。默认为"null_characters_not_allowed"。
-
StepValueValidator¶
-
class
StepValueValidator(limit_value, message=None)[源代码]¶ Raises a
ValidationErrorwith a code of'step_size'ifvalueis not an integral multiple oflimit_value, which can be a float, integer or decimal value or a callable.