def foo(request): if request.method=="POST": regForm=RegForm(request.POST) if regForm.is_valid(): pass # 可用数据: regForm.cleaned_data, # 将数据插入数据库表中 else: pass # 可用数据: regForm.errors # 可以利用模板渲染讲errors嵌套到页面中返回 # 也可以打包到一个字典中,用于ajax返回 else: regForm=RegForm() return render(request,"register.html",{"regForm":regForm}) ''' 实例化时: self.fields={ "username":"字段规则对象", "password":"字段规则对象", } is_valid时: self._errors = {} self.cleaned_data = {} #局部钩子: for name, field in self.fields.items(): try: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) # 全局钩子: self.clean() # def self.clean():return self.cleaned_data return not self.errors # True或者False '''
示例:
from django import forms class LoginForm(forms.Form): username = forms.CharField(label='username', max_length=100) password = forms.CharField(label='password', max_length=100) #钩子函数为对应字段添加判断条件 def clean_username(self): if len(self.cleaned_data.get("username"))>5: print(self.cleaned_data.get("password")) return self.cleaned_data.get("username") def clean_password(self): pass #全局钩子函数 def clean(self): if self.cleaned_data["password"] == self.cleaned_data["repeat_password"]: return self.cleaned_data
以上只是form组件的钩子简单介绍,想看具体的form组件介绍,请前往:http://www.cnblogs.com/gaoya666/articles/8762397.html