Django的validator验证器

django的 validator验证器 和 model的full_clean()回调的三种方法

一、验证模型model的三种方法

1
2
3
Model.clean_fields() # 验证模型的字段
Model.clean() # 验证整个模型
Model.validate_unique() # 验证字段的唯一

注:

① 这三种方法会在full_clean中依次回调,如果validate_unique = True,则会调用第三个方法。

full_clean方法不会再model.save()中回调,因此我们在调用基类的save()方法时,需要先手动回调full_clean()方法。

full_clean()的源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
def full_clean(self, exclude=None, validate_unique=True):
"""
Call clean_fields(), clean(), and validate_unique() on the model.
Raise a ValidationError for any errors that occur.
"""
errors = {}
if exclude is None:
exclude = []
else:
exclude = list(exclude)

try:
self.clean_fields(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)

# Form.clean() is run even if other validation fails, so do the
# same with Model.clean() for consistency.
try:
self.clean()
except ValidationError as e:
errors = e.update_error_dict(errors)

# Run unique checks, but only for fields that passed validation.
if validate_unique:
for name in errors:
if name != NON_FIELD_ERRORS and name not in exclude:
exclude.append(name)
try:
self.validate_unique(exclude=exclude)
except ValidationError as e:
errors = e.update_error_dict(errors)

if errors:
raise ValidationError(errors)

说明:观察源码可以发现,会依次调用上述的三个验证方法,如果触发了异常,首先会挨个捕捉异常,将errors写进NON_FIELD_ERRORS字典中,然后最后会统一抛出异常。

二、自定义验证器validator

自定义的验证器validator不会再model中进行回调,会在modelForm中进行回调,所以一般搭配modelForm使用。

例子:

1
2
3
4
5
6
7
8
class PhoneValidator(validators.RegexValidator):
"""正则表达式验证"""
regex = '^13[0-9]{1}[0-9]{8}|^15[0-9]{1}[0-9]{8}' # 正则表达式
message = _('请输入正确的手机号格式') # 错误提示消息
flags = 0 # 修饰符

def __init__(self, regex=regex, message=message, code=None, inverse_match=None, flags=flags):
super().__init__(regex,message,flags)

我们可以子类化RegexValidator类来实现自定义验证,RegexValidator类主要用于复杂的正则匹配。

当然了,django还提供了一些验证器。

比如:

MinValueValidator

class MinValueValidator(_minvalue, message=None)[source]

如果value小于min_value,抛出带有’min_value’代码的ValidationError异常。


MaxValueValidator

class MaxValueValidator(_maxvalue, message=None)[source]

如果value 大于 max_value,抛出带有’max_value’代码的ValidationError 异常。


MinLengthValidator

class MinLengthValidator(_minlength, message=None)[source]

如果value的长度小于min_length,抛出带有’min_length’代码的ValidationError异常。


MaxLengthValidator

class MaxLengthValidator(_maxlength, message=None)[source]

如果value的长度大于max_length,抛出带有’max_length’代码的ValidationError 异常。

等等,具体的可以去看源码from django.core import validators


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!