django model field validator 设置

转自:http://blog.csdn.net/cwjcwj520/article/details/17330845

 

 

例子为想在创建用户名的时候验证输入字符是否有效,并且插入了even_field为Category

model.py 中加入:

from django.core.exceptions import ValidationError
import re

def validate_letter(value):
    p = re.compile(r'^[\d\w_]{1,30}$')
    if p.match(value) == None:
        raise ValidationError(u"Username can only have digital, letter and '_'.")

def validate_even(value):
    print 'validate_even'
    if value % 2 != 0:
        raise ValidationError(u'%s is not an even number' % value)

class Category(models.Model):
    title = models.CharField(max_length=100, db_index=True, validators=[validate_letter])

    slug = models.SlugField(max_length=100, db_index=True)

    even_field = models.IntegerField(validators=[validate_even])

posted on 2018-01-15 21:33  枫飞飞  阅读(208)  评论(0编辑  收藏  举报