Django学习系列之Form验证

基与上篇文章,在这里我们用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])

结果:

wKioL1VbNxPCCpTGAAFFHw7nx10939.jpg

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

结果:

wKioL1VbOXWARHSLAAFKB8PxsZs615.jpg


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


结果:

wKiom1VbO6jSVULUAAEjh_kTA_c921.jpg


通过以上3种方式,我们便可以做些表单的验证了,我觉得这3种方式,已经满足我的需求了.

供参考!

你可能感兴趣的:(django,python,form,验证)