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 '''
示例:html
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.htmlpython