django的form提供了統一的結構化的後臺驗證機制,錯誤信息,也容易展示在前臺界面上。因爲python的面向對象,使得編寫html也可以代碼複用。css
def clean(self): """Checks that no two articles have the same title.""" if any(self.errors): # Don’t bother validating the formset unless each form is valid on its own return titles = [] for form in self.forms: title = form.cleaned_data[’title’] if title in titles: raise forms.ValidationError("Articles in a set must have distinct titles.") titles.append(title)
{{form.as_p}}, {{form.as_table}} ,{{form.as_url}}
{{form.hidden_fields}} 隱藏的字段html
{{form.visible_fields}} 顯示的字段python
{{form.media}}: 樣式與js定義文件django
{{form.non_field_errors}}:非字段相關的錯誤app
字段樣式定製,在python中:這種方式適合繼承,好比有好幾個頁面都須要使用該form,這種方式適合。less
domain_name=forms.CharField(widget=TextInput(attrs={"class":"form-control","size":"16","placeholder":"輸入您要加速的域名。如:image.a.com"}))
或者在html中dom
<input class="form-control" size="16" name="{{ form.domain_name.html_name }}" type="text" value="" placeholder="輸入您要加速的域名。如:image.a.com">
字段的屬性url
{{form.a.label}} 標籤名字spa
{{form.a.label_tag}} 標籤的html tag形式code
{{form.a.value}} 值
{{form.a.html_name}} input 的name
{{form.a.help_text}} input 的幫助
{{form.a.errors}} input 的錯誤
{{form.a.is_hidden}} input 是否隱藏
{{form.a.field}} a字段的各個屬性字典
2.widget:定製化form的字段的表現形式。
class CalendarWidget(forms.TextInput): class Media: css = { ’all’: (’pretty.css’,) } js = (’animations.js’, ’actions.js’) class CalendarWidget(forms.TextInput): def _media(self): return forms.Media(css={’all’: (’pretty.css’,)},js=(’animations.js’, ’actions.js’)) media = property(_media)