例子为想在创建用户名的时候验证输入字符是否有效,并且插入了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])
============================
注意事项:
1 用python manage.py shell 验证时,validationError,不会被抛出. 但是在admin中可以验证。
why?
2 如果要在models的class中插入新的数据项,需要删除原来database中的此table,不然无法插入新的field
a. 删除talbe,mysql命令:
drop table xxxx;
b. 重新创建数据库table
python manage.py syncdb