在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ 表單 API
點(diǎn)擊劫持保護(hù)
安全問題歸檔
Model 類參考
將遺留數(shù)據(jù)庫整合到Django
關(guān)聯(lián)對(duì)象參考
內(nèi)建基于類的視圖的API
聚合
Django 中的用戶認(rèn)證
django.contrib.humanize
Django管理文檔生成器
分頁
使用Django輸出CSV
加密簽名
文件儲(chǔ)存API
安全
Django中的測(cè)試
國際化和本地化
為Django編寫首個(gè)補(bǔ)丁
條件表達(dá)式
日志
模型元選項(xiàng)
部署靜態(tài)文件
執(zhí)行查詢
使用Django認(rèn)證系統(tǒng)
基于類的視圖
中間件
編寫自定義的django-admin命令
Django 的設(shè)置
格式本地化
數(shù)據(jù)庫訪問優(yōu)化
錯(cuò)誤報(bào)告
基于類的內(nèi)建通用視圖
編寫自定義存儲(chǔ)系統(tǒng)
編寫你的第一個(gè) Django 程序 第3部分
編寫數(shù)據(jù)庫遷移
使用表單
編寫你的第一個(gè) Django 程序 第2部分
編寫你的第一個(gè) Django 程序 第1部分
如何使用會(huì)話
系統(tǒng)檢查框架
新手入門
信號(hào)
編寫視圖
如何使用WSGI 部署
編寫你的第一個(gè)Django應(yīng)用,第6部分
常見的網(wǎng)站應(yīng)用工具
Widgets
內(nèi)建的視圖
模型實(shí)例參考
視圖層
Django中的密碼管理
高級(jí)教程:如何編寫可重用的應(yīng)用
國際化和本地化
"本地特色"附加功能
TemplateResponse 和 SimpleTemplateResponse
模式編輯器
文件上傳
快速安裝指南
部署 Django
表單 API
表單素材 ( <code>Media</code> 類)
管理文件
其它核心功能
查找 API 參考
表單
Admin
數(shù)據(jù)庫函數(shù)
自定義查找
使用基于類的視圖處理表單
管理操作
開發(fā)過程
編寫你的第一個(gè)Django應(yīng)用,第5部分
進(jìn)行原始的sql查詢
模型層
多數(shù)據(jù)庫
編寫你的第一個(gè) Django 程序 第4部分
Django安全
Django 初探
Django異常
重定向應(yīng)用
按需內(nèi)容處理
管理器
視圖裝飾器
驗(yàn)證器
使用Django輸出PDF
File對(duì)象
Django 的快捷函數(shù)
基于類的通用視圖 —— 索引
為模型提供初始數(shù)據(jù)
模板層
URL調(diào)度器
中間件
模型

表單 API

關(guān)于這篇文檔

這篇文檔講述Django 表單API 的詳細(xì)細(xì)節(jié)。你應(yīng)該先閱讀表單簡(jiǎn)介

綁定的表單和未綁定的表單

表單要么是綁定的,要么是未綁定的

  • 如果是綁定的,那么它能夠驗(yàn)證數(shù)據(jù),并渲染表單及其數(shù)據(jù)成HTML。
  • 如果是未綁定的,那么它不能夠完成驗(yàn)證(因?yàn)闆]有可驗(yàn)證的數(shù)據(jù)?。侨匀荒茕秩究瞻椎谋韱纬蒆TML。

class Form

若要?jiǎng)?chuàng)建一個(gè)未綁定的表單實(shí)例,只需簡(jiǎn)單地實(shí)例化該類:

>>> f = ContactForm()

若要綁定數(shù)據(jù)到表單,可以將數(shù)據(jù)以字典的形式傳遞給表單類的構(gòu)造函數(shù)的第一個(gè)參數(shù):

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)

在這個(gè)字典中,鍵為字段的名稱,它們對(duì)應(yīng)于表單類中的屬性。值為需要驗(yàn)證的數(shù)據(jù)。它們通常為字符串,但是沒有強(qiáng)制要求必須是字符串;傳遞的數(shù)據(jù)類型取決于字段,我們稍后會(huì)看到。

Form.``is_bound

如果運(yùn)行時(shí)刻你需要區(qū)分綁定的表單和未綁定的表單,可以檢查下表單is_bound 屬性的值:

>>> f = ContactForm()
>>> f.is_bound
False
>>> f = ContactForm({'subject': 'hello'})
>>> f.is_bound
True

注意,傳遞一個(gè)空的字典將創(chuàng)建一個(gè)帶有空數(shù)據(jù)的_綁定的_表單:

>>> f = ContactForm({})
>>> f.is_bound
True

如果你有一個(gè)綁定的表單實(shí)例但是想改下數(shù)據(jù),或者你想綁定一個(gè)未綁定的表單表單到某些數(shù)據(jù),你需要?jiǎng)?chuàng)建另外一個(gè)表單實(shí)例。Form 實(shí)例的數(shù)據(jù)沒有辦法修改。表單實(shí)例一旦創(chuàng)建,你應(yīng)該將它的數(shù)據(jù)視為不可變的,無論它有沒有數(shù)據(jù)。

使用表單來驗(yàn)證數(shù)據(jù)

Form.``clean()

當(dāng)你需要為相互依賴的字段添加自定義的驗(yàn)證時(shí),你可以實(shí)現(xiàn)表單clean()方法。示例用法參見Cleaning and validating fields that depend on each other

Form.``is_valid()

表單對(duì)象的首要任務(wù)就是驗(yàn)證數(shù)據(jù)。對(duì)于綁定的表單實(shí)例,可以調(diào)用is_valid()方法來執(zhí)行驗(yàn)證并返回一個(gè)表示數(shù)據(jù)是否合法的布爾值。

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True

讓我們?cè)囅路欠ǖ臄?shù)據(jù)。下面的情形中,subject 為空(默認(rèn)所有字段都是必需的)且sender 是一個(gè)不合法的郵件地址:

>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False

Form.``errors

訪問errors 屬性可以獲得錯(cuò)誤信息的一個(gè)字典:

>>> f.errors
{'sender': ['Enter a valid email address.'], 'subject': ['This field is required.']}

在這個(gè)字典中,鍵為字段的名稱,值為表示錯(cuò)誤信息的Unicode 字符串組成的列表。錯(cuò)誤信息保存在列表中是因?yàn)樽侄慰赡苡卸鄠€(gè)錯(cuò)誤信息。

你可以在調(diào)用is_valid() 之前訪問errors。表單的數(shù)據(jù)將在第一次調(diào)用is_valid() 或者訪問errors 時(shí)驗(yàn)證。

驗(yàn)證將值調(diào)用一次,無論你訪問errors 或者調(diào)用is_valid() 多少次。這意味著,如果驗(yàn)證過程有副作用,這些副作用將只觸發(fā)一次。

Form.errors.``as_data()

New in Django 1.7.

返回一個(gè)字典,它映射字段到原始的ValidationError 實(shí)例。

>>> f.errors.as_data()
{'sender': [ValidationError(['Enter a valid email address.'])],
'subject': [ValidationError(['This field is required.'])]}

每當(dāng)你需要根據(jù)錯(cuò)誤的code 來識(shí)別錯(cuò)誤時(shí),可以調(diào)用這個(gè)方法。它可以用來重寫錯(cuò)誤信息或者根據(jù)特定的錯(cuò)誤編寫自定義的邏輯。它還可以用來序列化錯(cuò)誤為一個(gè)自定義的格式(例如,XML);as_json() 就依賴于as_data()

需要as_data() 方法是為了向后兼容。以前,ValidationError 實(shí)例在它們渲染后 的錯(cuò)誤消息一旦添加到Form.errors 字典就立即被丟棄。理想情況下,Form.errors 應(yīng)該已經(jīng)保存ValidationError 實(shí)例而帶有as_ 前綴的方法可以渲染它們,但是為了不破壞直接使用Form.errors 中的錯(cuò)誤消息的代碼,必須使用其它方法來實(shí)現(xiàn)。

Form.errors.``as_json(_escapehtml=False)

New in Django 1.7.

返回JSON 序列化后的錯(cuò)誤。

>>> f.errors.as_json()
{"sender": [{"message": "Enter a valid email address.", "code": "invalid"}],
"subject": [{"message": "This field is required.", "code": "required"}]}

默認(rèn)情況下,as_json() 不會(huì)轉(zhuǎn)義它的輸出。如果你正在使用AJAX 請(qǐng)求表單視圖,而客戶端會(huì)解析響應(yīng)并將錯(cuò)誤插入到頁面中,你必須在客戶端對(duì)結(jié)果進(jìn)行轉(zhuǎn)義以避免可能的跨站腳本攻擊。使用一個(gè)JavaScript 庫比如jQuery 來做這件事很簡(jiǎn)單 —— 只要使用$(el).text(errorText) 而不是.html() 就可以。

如果由于某種原因你不想使用客戶端的轉(zhuǎn)義,你還可以設(shè)置escape_html=True,這樣錯(cuò)誤消息將被轉(zhuǎn)義而你可以直接在HTML 中使用它們。

Form.``add_error(field, error)

New in Django 1.7.

這個(gè)方法允許在Form.clean() 方法內(nèi)部或從表單的外部一起給字段添加錯(cuò)誤信息;例如從一個(gè)視圖中。

field 參數(shù)為字段的名稱。如果值為None,error 將作為Form.non_field_errors() 返回的一個(gè)非字段錯(cuò)誤。

error 參數(shù)可以是一個(gè)簡(jiǎn)單的字符串,或者最好是一個(gè)ValidationError 實(shí)例。引發(fā)ValidationError 中可以看到定義表單錯(cuò)誤時(shí)的最佳實(shí)踐。

注意,Form.add_error() 會(huì)自動(dòng)刪除cleaned_data 中的相關(guān)字段。

Form.``has_error(field, code=None)

New in Django 1.8.

這個(gè)方法返回一個(gè)布爾值,指示一個(gè)字段是否具有指定錯(cuò)誤code 的錯(cuò)誤。當(dāng)codeNone 時(shí),如果字段有任何錯(cuò)誤它都將返回True。

若要檢查非字段錯(cuò)誤,使用NON_FIELD_ERRORS 作為field 參數(shù)。

Form.``non_field_errors()

這個(gè)方法返回Form.errors 中不是與特定字段相關(guān)聯(lián)的錯(cuò)誤。它包含在Form.clean() 中引發(fā)的ValidationError 和使用Form.add_error(None, "...") 添加的錯(cuò)誤。

未綁定表單的行為

驗(yàn)證沒有綁定數(shù)據(jù)的表單是沒有意義的,下面的例子展示了這種情況:

>>> f = ContactForm()
>>> f.is_valid()
False
>>> f.errors
{}

動(dòng)態(tài)的初始值

Form.``initial

表單字段的初始值使用initial聲明。例如,你可能希望使用當(dāng)前會(huì)話的用戶名填充username字段。

使用Forminitial參數(shù)可以實(shí)現(xiàn)。該參數(shù)是字段名到初始值的一個(gè)字典。只需要包含你期望給出初始值的字段;不需要包含表單中的所有字段。例如:

>>> f = ContactForm(initial={'subject': 'Hi there!'})

這些值只顯示在沒有綁定的表單中,即使沒有提供特定值它們也不會(huì)作為后備的值。

注意,如果字段有定義initial, _而_實(shí)例化表單時(shí)也提供initial,那么后面的initial 將優(yōu)先。在下面的例子中,initial 在字段和表單實(shí)例化中都有定義,此時(shí)后者具有優(yōu)先權(quán):

>>> from django import forms
>>> class CommentForm(forms.Form):
...     name = forms.CharField(initial='class')
...     url = forms.URLField()
...     comment = forms.CharField()
>>> f = CommentForm(initial={'name': 'instance'}, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="instance" /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" /></td></tr>

檢查表單數(shù)據(jù)是否改變

Form.``has_changed()

當(dāng)你需要檢查表單的數(shù)據(jù)是否從初始數(shù)據(jù)發(fā)生改變時(shí),可以使用表單has_changed() 方法。

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data, initial=data)
>>> f.has_changed()
False

當(dāng)提交表單時(shí),我們可以重新構(gòu)建表單并提供初始值,這樣可以實(shí)現(xiàn)比較:

>>> f = ContactForm(request.POST, initial=data)
>>> f.has_changed()

如果request.POST 中的數(shù)據(jù)與initial 中的不同,has_changed() 將為True,否則為False。 計(jì)算的結(jié)果是通過調(diào)用表單每個(gè)字段的Field.has_changed() 得到的。

從表單中訪問字段

Form.``fields

你可以從表單實(shí)例的fields屬性訪問字段:

>>> for row in f.fields.values(): print(row)
...
<django.forms.fields.CharField object at 0x7ffaac632510>
<django.forms.fields.URLField object at 0x7ffaac632f90>
<django.forms.fields.CharField object at 0x7ffaac3aa050>
>>> f.fields['name']
<django.forms.fields.CharField object at 0x7ffaac6324d0>

可你可以修改表單實(shí)例的字段來改變字段在表單中的表示:

>>> f.as_table().split('\n')[0]
'<tr><th>Name:</th><td><input name="name" type="text" value="instance" /></td></tr>'
>>> f.fields['name'].label = "Username"
>>> f.as_table().split('\n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="instance" /></td></tr>'

注意不要改變base_fields 屬性,因?yàn)橐坏┬薷膶⒂绊懲粋€(gè)Python 進(jìn)程中接下來所有的ContactForm 實(shí)例:

>>> f.base_fields['name'].label = "Username"
>>> another_f = CommentForm(auto_id=False)
>>> another_f.as_table().split('\n')[0]
'<tr><th>Username:</th><td><input name="name" type="text" value="class" /></td></tr>'

訪問“清潔”的數(shù)據(jù)

Form.``cleaned_data

表單類中的每個(gè)字段不僅負(fù)責(zé)驗(yàn)證數(shù)據(jù),還負(fù)責(zé)“清潔”它們 —— 將它們轉(zhuǎn)換為正確的格式。這是個(gè)非常好用的功能,因?yàn)樗试S字段以多種方式輸入數(shù)據(jù),并總能得到一致的輸出。

例如,DateField 將輸入轉(zhuǎn)換為Python 的 datetime.date 對(duì)象。無論你傳遞的是'1994-07-15' 格式的字符串、datetime.date 對(duì)象、還是其它格式的數(shù)字,DateField 將始終將它們轉(zhuǎn)換成datetime.date 對(duì)象,只要它們是合法的。

一旦你創(chuàng)建一個(gè)表單實(shí)例并通過驗(yàn)證后,你就可以通過它的cleaned_data 屬性訪問清潔的數(shù)據(jù):

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

注意,文本字段 —— 例如,CharFieldEmailField —— 始終將輸入轉(zhuǎn)換為Unicode 字符串。我們將在這篇文檔的后面將是編碼的影響。

如果你的數(shù)據(jù)沒有 通過驗(yàn)證,cleaned_data 字典中只包含合法的字段:

>>> data = {'subject': '',
...         'message': 'Hi there',
...         'sender': 'invalid email address',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> f.is_valid()
False
>>> f.cleaned_data
{'cc_myself': True, 'message': 'Hi there'}

cleaned_data 始終 包含表單中定義的字段,即使你在構(gòu)建表單 時(shí)傳遞了額外的數(shù)據(jù)。在下面的例子中,我們傳遞一組額外的字段給ContactForm 構(gòu)造函數(shù),但是cleaned_data 將只包含表單的字段:

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True,
...         'extra_field_1': 'foo',
...         'extra_field_2': 'bar',
...         'extra_field_3': 'baz'}
>>> f = ContactForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data # Doesn't contain extra_field_1, etc.
{'cc_myself': True, 'message': 'Hi there', 'sender': 'foo@example.com', 'subject': 'hello'}

當(dāng)表單合法時(shí),cleaned_data 將包含_所有_字段的鍵和值,即使傳遞的數(shù)據(jù)不包含某些可選字段的值。在下面的例子中,傳遞的數(shù)據(jù)字典不包含nick_name 字段的值,但是cleaned_data 任然包含它,只是值為空:

>>> from django.forms import Form
>>> class OptionalPersonForm(Form):
...     first_name = CharField()
...     last_name = CharField()
...     nick_name = CharField(required=False)
>>> data = {'first_name': 'John', 'last_name': 'Lennon'}
>>> f = OptionalPersonForm(data)
>>> f.is_valid()
True
>>> f.cleaned_data
{'nick_name': '', 'first_name': 'John', 'last_name': 'Lennon'}

在上面的例子中,cleaned_datanick_name 設(shè)置為一個(gè)空字符串,這是因?yàn)?code>nick_name 是CharFieldCharField 將空值作為一個(gè)空字符串。每個(gè)字段都知道自己的“空”值 —— 例如,DateField 的空值是None 而不是一個(gè)空字符串。關(guān)于每個(gè)字段空值的完整細(xì)節(jié),參見“內(nèi)建的Field 類”一節(jié)中每個(gè)字段的“空值”提示。

你可以自己編寫代碼來對(duì)特定的字段(根據(jù)它們的名字)或者表單整體(考慮到不同字段的組合)進(jìn)行驗(yàn)證。更多信息參見表單和字段驗(yàn)證

輸出表單為HTML

表單對(duì)象的第二個(gè)任務(wù)是將它渲染成HTML。很簡(jiǎn)單,print 它:

>>> f = ContactForm()
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>

如果表單是綁定的,輸出的HTML 將包含數(shù)據(jù)。例如,如果字段是<input type="text"> 的形式,其數(shù)據(jù)將位于value 屬性中。如果字段是<input type="checkbox"> 的形式,HTML 將包含checked="checked"

>>> data = {'subject': 'hello',
...         'message': 'Hi there',
...         'sender': 'foo@example.com',
...         'cc_myself': True}
>>> f = ContactForm(data)
>>> print(f)
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" value="hello" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" value="Hi there" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" value="foo@example.com" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" checked="checked" /></td></tr>

默認(rèn)的輸出時(shí)具有兩個(gè)列的HTML 表格,每個(gè)字段對(duì)應(yīng)一個(gè)<tr>。注意事項(xiàng):

  • 為了靈活性,輸出_不_包含<table></table><form></form> 以及<input type="submit"> 標(biāo)簽。你需要添加它們。
  • 每個(gè)字段類型有一個(gè)默認(rèn)的HTML 表示。CharField 表示為一個(gè)<input type="text">EmailField 表示為一個(gè)<input type="email">。BooleanField 表示為一個(gè)<input type="checkbox">。注意,這些只是默認(rèn)的表示;你可以使用Widget 指定字段使用哪種HTML,我們將稍后解釋。
  • 每個(gè)標(biāo)簽的HTML name 直接從ContactForm 類中獲取。
  • 每個(gè)字段的文本標(biāo)簽 —— 例如'Subject:'、'Message:''Cc myself:' 通過將所有的下劃線轉(zhuǎn)換成空格并大寫第一個(gè)字母生成。再次提醒,這些只是默認(rèn)的表示;你可以手工指定標(biāo)簽。
  • 每個(gè)文本標(biāo)簽周圍有一個(gè)HTML <label> 標(biāo)簽,它指向表單字段的id。這個(gè)id,是通過在字段名稱前面加上'id_' 前綴生成。id 屬性和<label> 標(biāo)簽?zāi)J(rèn)包含在輸出中,但你可以改變這一行為。

雖然print 表單時(shí)<table> 是默認(rèn)的輸出格式,但是還有其它格式可用。每個(gè)格式對(duì)應(yīng)于表單對(duì)象的一個(gè)方法,每個(gè)方法都返回一個(gè)Unicode 對(duì)象。

as_p()

Form.``as_p()

as_p() 渲染表單為一系列的<p> 標(biāo)簽,每個(gè)<p> 標(biāo)簽包含一個(gè)字段:

>>> f = ContactForm()
>>> f.as_p()
'<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>\n<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>\n<p><label for="id_sender">Sender:</label> <input type="text" name="sender" id="id_sender" /></p>\n<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>'
>>> print(f.as_p())
<p><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></p>
<p><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></p>
<p><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></p>

as_ul()

Form.``as_ul()

as_ul() 渲染表單為一系列的<li>標(biāo)簽,每個(gè)<li> 標(biāo)簽包含一個(gè)字段。它_不_包含<ul></ul>,所以你可以自己指定<ul> 的任何HTML 屬性:

>>> f = ContactForm()
>>> f.as_ul()
'<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>\n<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>\n<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>\n<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>'
>>> print(f.as_ul())
<li><label for="id_subject">Subject:</label> <input id="id_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_message">Message:</label> <input type="text" name="message" id="id_message" /></li>
<li><label for="id_sender">Sender:</label> <input type="email" name="sender" id="id_sender" /></li>
<li><label for="id_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_cc_myself" /></li>

as_table()

Form.``as_table()

最后,as_table()輸出表單為一個(gè)HTML <table>。它與print 完全相同。事實(shí)上,當(dāng)你print 一個(gè)表單對(duì)象時(shí),在后臺(tái)調(diào)用的就是as_table() 方法:

>>> f = ContactForm()
>>> f.as_table()
'<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>\n<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>\n<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>\n<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>'
>>> print(f.as_table())
<tr><th><label for="id_subject">Subject:</label></th><td><input id="id_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
<tr><th><label for="id_sender">Sender:</label></th><td><input type="email" name="sender" id="id_sender" /></td></tr>
<tr><th><label for="id_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_cc_myself" /></td></tr>

表單必填行和錯(cuò)誤行的樣式

Form.``error_css_class

Form.``required_css_class

將必填的表單行和有錯(cuò)誤的表單行定義不同的樣式特別常見。例如,你想將必填的表單行以粗體顯示、將錯(cuò)誤以紅色顯示。

表單類具有一對(duì)鉤子,可以使用它們來添加class 屬性給必填的行或有錯(cuò)誤的行:只需簡(jiǎn)單地設(shè)置Form.error_css_class 和/或 Form.required_css_class 屬性:

from django.forms import Form

class ContactForm(Form):
    error_css_class = 'error'
    required_css_class = 'required'

    # ... and the rest of your fields here

一旦你設(shè)置好,將根據(jù)需要設(shè)置行的"error" 和/或"required" CSS 類型。 其HTML 看上去將類似:

>>> f = ContactForm(data)
>>> print(f.as_table())
<tr class="required"><th><label class="required" for="id_subject">Subject:</label>    ...
<tr class="required"><th><label class="required" for="id_message">Message:</label>    ...
<tr class="required error"><th><label class="required" for="id_sender">Sender:</label>      ...
<tr><th><label for="id_cc_myself">Cc myself:<label> ...
>>> f['subject'].label_tag()
<label class="required" for="id_subject">Subject:</label>
>>> f['subject'].label_tag(attrs={'class': 'foo'})
<label for="id_subject" class="foo required">Subject:</label>

Changed in Django 1.8:

required_css_class 添加到<label> 標(biāo)簽,如上面所看到的。

配置表單元素的HTML id 屬性和 <label> 標(biāo)簽

Form.``auto_id

默認(rèn)情況下,表單的渲染方法包含:

  • 表單元素的HTML id 屬性
  • 對(duì)應(yīng)的<label> 標(biāo)簽。HTML <label> 標(biāo)簽指示標(biāo)簽文本關(guān)聯(lián)的表單元素。這個(gè)小小的改進(jìn)讓表單在輔助設(shè)備上具有更高的可用性。使用<label> 標(biāo)簽始終是個(gè)好想法。

id 屬性值通過在表單字段名稱的前面加上id_ 生成。但是如果你想改變id 的生成方式或者完全刪除 HTML id 屬性和<label>標(biāo)簽,這個(gè)行為是可配置的。

id 和label 的行為使用表單構(gòu)造函數(shù)的auto_id 參數(shù)控制。這個(gè)參數(shù)必須為TrueFalse 或者一個(gè)字符串。

如果auto_idFalse,那么表單的輸出將不包含<label> 標(biāo)簽和id 屬性:

>>> f = ContactForm(auto_id=False)
>>> print(f.as_table())
<tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" /></td></tr>
<tr><th>Message:</th><td><input type="text" name="message" /></td></tr>
<tr><th>Sender:</th><td><input type="email" name="sender" /></td></tr>
<tr><th>Cc myself:</th><td><input type="checkbox" name="cc_myself" /></td></tr>
>>> print(f.as_ul())
<li>Subject: <input type="text" name="subject" maxlength="100" /></li>
<li>Message: <input type="text" name="message" /></li>
<li>Sender: <input type="email" name="sender" /></li>
<li>Cc myself: <input type="checkbox" name="cc_myself" /></li>
>>> print(f.as_p())
<p>Subject: <input type="text" name="subject" maxlength="100" /></p>
<p>Message: <input type="text" name="message" /></p>
<p>Sender: <input type="email" name="sender" /></p>
<p>Cc myself: <input type="checkbox" name="cc_myself" /></p>

如果auto_id 設(shè)置為True,那么輸出的表示 包含<label> 標(biāo)簽并簡(jiǎn)單地使用字典名稱作為每個(gè)表單字段的id

>>> f = ContactForm(auto_id=True)
>>> print(f.as_table())
<tr><th><label for="subject">Subject:</label></th><td><input id="subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="message">Message:</label></th><td><input type="text" name="message" id="message" /></td></tr>
<tr><th><label for="sender">Sender:</label></th><td><input type="email" name="sender" id="sender" /></td></tr>
<tr><th><label for="cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="cc_myself" /></td></tr>
>>> print(f.as_ul())
<li><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="message">Message:</label> <input type="text" name="message" id="message" /></li>
<li><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></li>
<li><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></li>
>>> print(f.as_p())
<p><label for="subject">Subject:</label> <input id="subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="message">Message:</label> <input type="text" name="message" id="message" /></p>
<p><label for="sender">Sender:</label> <input type="email" name="sender" id="sender" /></p>
<p><label for="cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="cc_myself" /></p>

如果auto_id 設(shè)置為包含格式字符'%s' 的字符串,那么表單的輸出將包含<label> 標(biāo)簽,并將根據(jù)格式字符串生成id 屬性。例如,對(duì)于格式字符串'field_%s',名為subject 的字段的id 值將是'field_subject'。繼續(xù)我們的例子:

>>> f = ContactForm(auto_id='id_for_%s')
>>> print(f.as_table())
<tr><th><label for="id_for_subject">Subject:</label></th><td><input id="id_for_subject" type="text" name="subject" maxlength="100" /></td></tr>
<tr><th><label for="id_for_message">Message:</label></th><td><input type="text" name="message" id="id_for_message" /></td></tr>
<tr><th><label for="id_for_sender">Sender:</label></th><td><input type="email" name="sender" id="id_for_sender" /></td></tr>
<tr><th><label for="id_for_cc_myself">Cc myself:</label></th><td><input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></td></tr>
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
>>> print(f.as_p())
<p><label for="id_for_subject">Subject:</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></p>
<p><label for="id_for_message">Message:</label> <input type="text" name="message" id="id_for_message" /></p>
<p><label for="id_for_sender">Sender:</label> <input type="email" name="sender" id="id_for_sender" /></p>
<p><label for="id_for_cc_myself">Cc myself:</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></p>

如果auto_id 設(shè)置為任何其它的真值 —— 例如不包含%s 的字符串 —— 那么其行為將類似auto_id 等于True。

默認(rèn)情況下,auto_id 設(shè)置為'id_%s'

Form.``label_suffix

一個(gè)字符串(默認(rèn)為英文的:),表單渲染時(shí)將附加在每個(gè)label 名稱的后面。

使用label_suffix 參數(shù)可以自定義這個(gè)字符,或者完全刪除它:

>>> f = ContactForm(auto_id='id_for_%s', label_suffix='')
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject</label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message</label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender</label> <input type="email" name="sender" id="id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself</label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>
>>> f = ContactForm(auto_id='id_for_%s', label_suffix=' ->')
>>> print(f.as_ul())
<li><label for="id_for_subject">Subject -></label> <input id="id_for_subject" type="text" name="subject" maxlength="100" /></li>
<li><label for="id_for_message">Message -></label> <input type="text" name="message" id="id_for_message" /></li>
<li><label for="id_for_sender">Sender -></label> <input type="email" name="sender" id="id_for_sender" /></li>
<li><label for="id_for_cc_myself">Cc myself -></label> <input type="checkbox" name="cc_myself" id="id_for_cc_myself" /></li>

注意,該標(biāo)簽后綴只有當(dāng)label 的最后一個(gè)字符不是表單符號(hào)(., !