基与上篇文章,在这里我们用3种方式来验证表单.
1.表单字段的验证器
详见:https://docs.djangoproject.com/en/1.6/ref/validators/
from django.core.exceptions import ValidationError def validate_nickname(value): if value == "badboy": raise ValidationError(u‘%s is private,dont input‘ % value) class Register(forms.Form): nickname = forms.CharField(max_length=20,label="昵称",help_text="请输入您的别名!",widget=forms.Te xtInput(attrs={‘class‘:‘special‘,‘id‘:‘nick‘}),error_messages={‘required‘:u‘别名不能为空‘},validators =[validate_nickname])
结果:
2.clean_filedname,验证字段
class Register(forms.Form):
..........................................
def clean_username(self):
username = self.cleaned_data.get(‘username‘)
if username == "badboy":
raise ValidationError(u‘%s被使用了,请换个名字!‘ % username)
else:
return username
结果:
3.表单clean方法
class Register(forms.Form):
............................................
def clean(self):
cleaned_data = super(Register,self).clean()
nickname = cleaned_data.get(‘nickname‘)
username = cleaned_data.get(‘username‘)
if nickname == username:
self._errors[‘username‘] = self.error_class([u"别名与用户名不能一样!"])
else:
return cleaned_data
结果:
通过以上3种方式,我们便可以做些表单的验证了,我觉得这3种方式,已经满足我的需求了.
供参考!
本文出自 “坏男孩” 博客,请务必保留此出处http://5ydycm.blog.51cto.com/115934/1652953
原文地址:http://5ydycm.blog.51cto.com/115934/1652953