Django Validators - WBowam/wbowam.github.com GitHub Wiki
Date: 2014-09-07
Title: Django Validators
Tags: Django
Category: It
之前没用过Validators
这回入了门,用了一下,很爽~~
from django.core.exceptions import ValidationError
def validate_even(value):
if value % 2 != 0:
raise ValidationError('%s is not an even number' % value)
You can add this to a model field via the field’s validators argument:
from django.db import models
class MyModel(models.Model):
even_field = models.IntegerField(validators=[validate_even])
神奇点在于,django自动帮我们抓取‘值’当作参数传入我们的Validators(有点像让人讨厌的黑魔术,但不是~~)
from django import forms
class MyForm(forms.Form):
even_field = forms.IntegerField(validators=[validate_even])
用法如下:
from django.core.validators import MinLengthValidator
from django.db import models
class MyModel(models.Model):
even_field = models.TextField(validators=[MinLengthValidator(20)])
以上所用MinLengthValidator
网名生意:max_length
的反意思。
还有很多内置Validator,看官网
1.自己写一个子类,覆盖message
from django.core.validators import MinLengthValidator
from django.db import models
class MyMinLengthValidator(MinLengthValidator):
message = "少年, 至少输入%(limit_value)d个字符 ,(你怎么只输入 %(show_value)d个字符就完事儿啊)."
class MyModel(models.Model):
even_field = models.TextField(validators=[MinLengthValidator(20)])
- 当然,这种方法很简单,很常见,不够高大上:填写
error_messages
选项
....
my_field = forms.CharField(validators=[MinLengthValidator(8)],
error_messages={"min_length":"少年, 至少输入%(limit_value)d个字符 ,(你怎么只输入 %(show_value)d个字符就完事儿啊)."})
})
.. . ..