Django表單字段彙總

Field.clean(value)[source]

雖然表單字段的Field類主要使用在Form類中,但也能夠直接實例化它們來使用,以便更好地瞭解它們是如何工做的。每一個Field的實例都有一個clean()方法,它接受一個參數,而後返回「清潔的」數據或者拋出一個django.forms.ValidationError異常:前端

>>> from django import forms >>> f = forms.EmailField() >>> f.clean('foo@example.com') 'foo@example.com' >>> f.clean('invalid email address') Traceback (most recent call last): ... ValidationError: ['Enter a valid email address.'] 

這個clean方法常常被咱們用來在開發或測試過程當中對數據進行驗證和測試。git

1、核心字段參數

如下的參數是每一個Field類均可以使用的。web

1. required

給字段添加必填屬性,不能空着。正則表達式

>>> from django import forms >>> f = forms.CharField() >>> f.clean('foo') 'foo' >>> f.clean('') Traceback (most recent call last): ... ValidationError: ['This field is required.'] >>> f.clean(None) Traceback (most recent call last): ... ValidationError: ['This field is required.'] >>> f.clean(' ') ' ' >>> f.clean(0) '0' >>> f.clean(True) 'True' >>> f.clean(False) 'False' 

若要表示一個字段不是必需的,設置required=False:django

>>> f = forms.CharField(required=False)
>>> f.clean('foo')
'foo'
>>> f.clean('')
''
>>> f.clean(None)
''
>>> f.clean(0)
'0'
>>> f.clean(True)
'True'
>>> f.clean(False)
'False'

2. label

label參數用來給字段添加‘人類友好’的提示信息。若是沒有設置這個參數,那麼就用字段的首字母大寫名字。好比:服務器

下面的例子,前兩個字段有,最後的comment沒有label參數:函數

>>> from django import forms >>> class CommentForm(forms.Form): ... name = forms.CharField(label='Your name') ... url = forms.URLField(label='Your website', required=False) ... comment = forms.CharField() >>> f = CommentForm(auto_id=False) >>> print(f) <tr><th>Your name:</th><td><input type="text" name="name" required /></td></tr> <tr><th>Your website:</th><td><input type="url" name="url" /></td></tr> <tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr> 

3. label_suffix

Django默認爲上面的label參數後面加個冒號後綴,若是想自定義,可使用label_suffix參數。好比下面的例子用「?」代替了冒號:測試

>>> class ContactForm(forms.Form):
...     age = forms.IntegerField()
...     nationality = forms.CharField()
...     captcha_answer = forms.IntegerField(label='2 + 2', label_suffix=' =')
>>> f = ContactForm(label_suffix='?')
>>> print(f.as_p())
<p><label for="id_age">Age?</label> <input id="id_age" name="age" type="number" required /></p> <p><label for="id_nationality">Nationality?</label> <input id="id_nationality" name="nationality" type="text" required /></p> <p><label for="id_captcha_answer">2 + 2 =</label> <input id="id_captcha_answer" name="captcha_answer" type="number" required /></p> 

4. initial

爲HTML頁面中表單元素定義初始值。也就是input元素的value參數的值,以下所示:ui

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

你可能會問爲何不在渲染表單的時候傳遞一個包含初始化值的字典給它,不是更方便?由於若是這麼作,你將觸發表單的驗證過程,此時輸出的HTML頁面將包含驗證中產生的錯誤,以下所示:this

>>> class CommentForm(forms.Form):
...     name = forms.CharField()
...     url = forms.URLField()
...     comment = forms.CharField()
>>> default_data = {'name': 'Your name', 'url': 'http://'}
>>> f = CommentForm(default_data, auto_id=False)
>>> print(f)
<tr><th>Name:</th><td><input type="text" name="name" value="Your name" required /></td></tr> <tr><th>Url:</th><td><ul class="errorlist"><li>Enter a valid URL.</li></ul><input type="url" name="url" value="http://" required /></td></tr> <tr><th>Comment:</th><td><ul class="errorlist"><li>This field is required.</li></ul><input type="text" name="comment" required /></td></tr> 

這就是爲何initial參數只用在未綁定的表單上。

還要注意,若是提交表單時某個字段的值沒有填寫,initial的值不會做爲「默認」的數據。initial值只用於原始表單的顯示:

>>> class CommentForm(forms.Form):
...     name = forms.CharField(initial='Your name')
...     url = forms.URLField(initial='http://')
...     comment = forms.CharField()
>>> data = {'name': '', 'url': '', 'comment': 'Foo'}
>>> f = CommentForm(data)
>>> f.is_valid()
False
# The form does *not* fall back to using the initial values.
>>> f.errors
{'url': ['This field is required.'], 'name': ['This field is required.']}

除了常量以外,你還能夠傳遞一個可調用的對象:

>>> import datetime >>> class DateForm(forms.Form): ... day = forms.DateField(initial=datetime.date.today) >>> print(DateForm()) <tr><th>Day:</th><td><input type="text" name="day" value="12/23/2008" required /><td></tr> 

5. widget

最重要的參數之一,指定渲染Widget時使用的widget類,也就是這個form字段在HTML頁面中是顯示爲文本輸入框?密碼輸入框?單選按鈕?多選框?仍是別的....

6. help_text

該參數用於設置字段的輔助描述文本。

>>> from django import forms >>> class HelpTextContactForm(forms.Form): ... subject = forms.CharField(max_length=100, help_text='100 characters max.') ... message = forms.CharField() ... sender = forms.EmailField(help_text='A valid email address, please.') ... cc_myself = forms.BooleanField(required=False) >>> f = HelpTextContactForm(auto_id=False) >>> print(f.as_table()) <tr><th>Subject:</th><td><input type="text" name="subject" maxlength="100" required /><br /><span class="helptext">100 characters max.</span></td></tr> <tr><th>Message:</th><td><input type="text" name="message" required /></td></tr> <tr><th>Sender:</th><td><input type="email" name="sender" required /><br />A valid email address, please.</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" required /> <span class="helptext">100 characters max.</span></li> <li>Message: <input type="text" name="message" required /></li> <li>Sender: <input type="email" name="sender" required /> A valid email address, please.</li> <li>Cc myself: <input type="checkbox" name="cc_myself" /></li> >>> print(f.as_p()) <p>Subject: <input type="text" name="subject" maxlength="100" required /> <span class="helptext">100 characters max.</span></p> <p>Message: <input type="text" name="message" required /></p> <p>Sender: <input type="email" name="sender" required /> A valid email address, please.</p> <p>Cc myself: <input type="checkbox" name="cc_myself" /></p> 

7. error_messages

該參數容許你覆蓋字段引起異常時的默認信息。 傳遞的是一個字典,其鍵爲你想覆蓋的錯誤信息。 例如,下面是默認的錯誤信息:

>>> from django import forms >>> generic = forms.CharField() >>> generic.clean('') Traceback (most recent call last): ... ValidationError: ['This field is required.'] 

而下面是自定義的錯誤信息:

>>> name = forms.CharField(error_messages={'required': 'Please enter your name'})
>>> name.clean('')
Traceback (most recent call last):
  ...
ValidationError: ['Please enter your name']

能夠指定多種類型的鍵,不只僅針對‘requeired’錯誤,參考下面的內容。

8. validators

指定一個列表,其中包含了爲字段進行驗證的函數。也就是說,若是你自定義了驗證方法,不用Django內置的驗證功能,那麼要經過這個參數,將字段和自定義的驗證方法連接起來。

9. localize

localize參數幫助實現表單數據輸入的本地化。

10. disabled

設置有該屬性的字段在前端頁面中將顯示爲不可編輯狀態。

該參數接收布爾值,當設置爲True時,使用HTML的disabled屬性禁用表單域,以使用戶沒法編輯該字段。即便非法篡改了前端頁面的屬性,向服務器提交了該字段的值,也將依然被忽略。

2、 Django表單內置的Field類

對於每一個字段類,介紹其默認的widget,當輸入爲空時返回的值,以及採起何種驗證方式。‘規範化爲’表示轉換爲PYthon的何種對象。可用的錯誤信息鍵,表示該字段可自定義錯誤信息的類型(字典的鍵)。

1. BooleanField

  • 默認的Widget:CheckboxInput
  • 空值:False
  • 規範化爲:Python的True或者False
  • 可用的錯誤信息鍵:required

2. CharField

  • 默認的Widget:TextInput
  • 空值:與empty_value給出的任何值。
  • 規範化爲:一個Unicode 對象。
  • 驗證max_lengthmin_length,若是設置了這兩個參數。 不然,全部的輸入都是合法的。
  • 可用的錯誤信息鍵:min_length, max_length, required

有四個可選參數:

  • max_length,min_length:設置字符串的最大和最小長度。
  • strip:若是True(默認),去除輸入的前導和尾隨空格。
  • empty_value:用來表示「空」的值。 默認爲空字符串。

3. ChoiceField

  • 默認的Widget:Select
  • 空值:''(一個空字符串)
  • 規範化爲:一個Unicode 對象。
  • 驗證給定的值是否在選項列表中。
  • 可用的錯誤信息鍵:required, invalid_choice

參數choices:用來做爲該字段選項的一個二元組組成的可迭代對象(例如,列表或元組)或者一個可調用對象。格式與用於和ORM模型字段的choices參數相同。

4. TypedChoiceField

像ChoiceField同樣,只是還有兩個額外的參數:coerce和empty_value。

  • 默認的Widget:Select
  • 空值:empty_value參數設置的值。
  • 規範化爲:coerce參數類型的值。
  • 驗證給定的值在選項列表中存在而且能夠被強制轉換。
  • 可用的錯誤信息的鍵:required, invalid_choice

5. DateField

  • 默認的Widget:DateInput
  • 空值:None
  • 規範化爲:datetime.date對象。
  • 驗證給出的值是一個datetime.date、datetime.datetime 或指定日期格式的字符串。
  • 錯誤信息的鍵:required, invalid

接收一個可選的參數:input_formats。一個格式的列表,用於轉換字符串爲datetime.date對象。

若是沒有提供input_formats,默認的輸入格式爲:

['%Y-%m-%d',      # '2006-10-25'
 '%m/%d/%Y',      # '10/25/2006'
 '%m/%d/%y']      # '10/25/06'

另外,若是你在設置中指定USE_L10N=False,如下的格式也將包含在默認的輸入格式中:

['%b %d %Y',      # 'Oct 25 2006'
 '%b %d, %Y',     # 'Oct 25, 2006'
 '%d %b %Y',      # '25 Oct 2006'
 '%d %b, %Y',     # '25 Oct, 2006'
 '%B %d %Y',      # 'October 25 2006'
 '%B %d, %Y',     # 'October 25, 2006'
 '%d %B %Y',      # '25 October 2006'
 '%d %B, %Y']     # '25 October, 2006'

6. DateTimeField

  • 默認的Widget:DateTimeInput
  • 空值:None
  • 規範化爲:Python的datetime.datetime對象。
  • 驗證給出的值是一個datetime.datetime、datetime.date或指定日期格式的字符串。
  • 錯誤信息的鍵:required, invalid

接收一個可選的參數:input_formats

若是沒有提供input_formats,默認的輸入格式爲:

['%Y-%m-%d %H:%M:%S',    # '2006-10-25 14:30:59'
 '%Y-%m-%d %H:%M',       # '2006-10-25 14:30'
 '%Y-%m-%d',             # '2006-10-25'
 '%m/%d/%Y %H:%M:%S',    # '10/25/2006 14:30:59'
 '%m/%d/%Y %H:%M',       # '10/25/2006 14:30'
 '%m/%d/%Y',             # '10/25/2006'
 '%m/%d/%y %H:%M:%S',    # '10/25/06 14:30:59'
 '%m/%d/%y %H:%M',       # '10/25/06 14:30'
 '%m/%d/%y']             # '10/25/06'

7. DecimalField

  • 默認的Widget:當Field.localize是False時爲NumberInput,不然爲TextInput。
  • 空值:None
  • 規範化爲:Python decimal對象。
  • 驗證給定的值爲一個十進制數。 忽略前導和尾隨的空白。
  • 錯誤信息的鍵:max_whole_digitsmax_digitsmax_decimal_places,max_value, invalid, required,min_value

接收四個可選的參數:

max_value,min_value:容許的值的範圍,須要賦值decimal.Decimal對象,不能直接給個整數類型。

max_digits:值容許的最大位數(小數點以前和以後的數字總共的位數,前導的零將被刪除)。

decimal_places:容許的最大小數位。

8. DurationField

  • 默認的Widget:TextInput
  • 空值:None
  • 規範化爲:Python timedelta。
  • 驗證給出的值是一個字符串,並且能夠轉換爲timedelta對象。
  • 錯誤信息的鍵:required, invalid.

9. EmailField

  • 默認的Widget:EmailInput
  • 空值:''(一個空字符串)
  • 規範化爲:Unicode 對象。
  • 使用正則表達式驗證給出的值是一個合法的郵件地址。
  • 錯誤信息的鍵:required, invalid

兩個可選的參數用於驗證,max_length 和min_length。

10. FileField

  • 默認的Widget:ClearableFileInput
  • 空值:None
  • 規範化爲:一個UploadedFile對象,它封裝文件內容和文件名到一個對象內。
  • 驗證非空的文件數據已經綁定到表單。
  • 錯誤信息的鍵:missing, invalid, required, empty, max_length

具備兩個可選的參數用於驗證:max_length 和 allow_empty_file。

11. FilePathField

  • 默認的Widget:Select
  • 空值:None
  • 規範化爲:Unicode 對象。
  • 驗證選擇的選項在選項列表中存在。
  • 錯誤信息的鍵:required, invalid_choice

這個字段容許從一個特定的目錄選擇文件。 它有五個額外的參數,其中的path是必須的:

path:要列出的目錄的絕對路徑。 這個目錄必須存在。

recursive:若是爲False(默認值),只用直接位於path下的文件或目錄做爲選項。若是爲True,將遞歸訪問這個目錄,其內全部的子目錄和文件都將做爲選項。

match:正則表達模式;只有具備與此表達式匹配的文件名稱才被容許做爲選項。

allow_files:可選。默認爲True。表示是否應該包含指定位置的文件。它和allow_folders必須有一個爲True。

allow_folders可選。默認爲False。表示是否應該包含指定位置的目錄。

12. FloatField

  • 默認的Widget:當Field.localize是False時爲NumberInput,不然爲TextInput。
  • 空值:None
  • 規範化爲:Float 對象。
  • 驗證給定的值是一個浮點數。
  • 錯誤信息的鍵:max_value, invalid, required, min_value

接收兩個可選的參數用於驗證,max_value和min_value,控制容許的值的範圍。

13. ImageField

  • 默認的Widget:ClearableFileInput
  • 空值:None
  • 規範化爲:一個UploadedFile 象,它封裝文件內容和文件名爲一個單獨的對象。
  • 驗證文件數據已綁定到表單,而且該文件是Pillow能夠解析的圖像格式。
  • 錯誤信息的鍵:missing, invalid, required, empty, invalid_image

使用ImageField須要安裝Pillow(pip install pillow)。若是在上傳圖片時遇到圖像損壞錯誤,一般意味着使用了Pillow不支持的格式。

14. IntegerField

  • 默認的Widget:當Field.localize是False時爲NumberInput,不然爲TextInput。
  • 空值:None
  • 規範化爲:Python 整數或長整數。
  • 驗證給定值是一個整數。 容許前導和尾隨空格,相似Python的int()函數。
  • 錯誤信息的鍵:max_value, invalid, required, min_value

兩個可選參數:max_value和min_value,控制容許的值的範圍。

15. GenericIPAddressField

包含IPv4或IPv6地址的字段。

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:一個Unicode對象。
  • 驗證給定值是有效的IP地址。
  • 錯誤信息的鍵:required, invalid

有兩個可選參數:protocol和unpack_ipv4

16. MultipleChoiceField

  • 默認的Widget:SelectMultiple
  • 空值:[](一個空列表)
  • 規範化爲:一個Unicode 對象列表。
  • 驗證給定值列表中的每一個值都存在於選擇列表中。
  • 錯誤信息的鍵:invalid_list, invalid_choice, required

17. TypedMultipleChoiceField

相似MultipleChoiceField,除了須要兩個額外的參數,coerce和empty_value。

  • 默認的Widget:SelectMultiple
  • 空值:empty_value
  • 規範化爲:coerce參數提供的類型值列表。
  • 驗證給定值存在於選項列表中而且能夠強制。
  • 錯誤信息的鍵:required, invalid_choice

18. NullBooleanField

  • 默認的Widget:NullBooleanSelect
  • 空值:None
  • 規範化爲:Python None, False 或True 值。
  • 不驗證任何內容(即,它從不引起ValidationError)。

19.RegexField

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:一個Unicode 對象。
  • 驗證給定值與某個正則表達式匹配。
  • 錯誤信息的鍵:required, invalid

須要一個必需的參數:regex,須要匹配的正則表達式。

還能夠接收max_length,min_length和strip參數,相似CharField。

20. SlugField

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:一個Unicode 對象。
  • 驗證給定的字符串只包括字母、數字、下劃線及連字符。
  • 錯誤信息的鍵:required, invalid

此字段用於在表單中表示模型的SlugField。

21. TimeField

  • 默認的Widget:TextInput
  • 空值:None
  • 規範化爲:一個Python 的datetime.time 對象。
  • 驗證給定值是datetime.time或以特定時間格式格式化的字符串。
  • 錯誤信息的鍵:required, invalid

接收一個可選的參數:input_formats,用於嘗試將字符串轉換爲有效的datetime.time對象的格式列表。

若是沒有提供input_formats,默認的輸入格式爲:

'%H:%M:%S',     # '14:30:59'
'%H:%M',        # '14:30'

22. URLField

  • 默認的Widget:URLInput
  • 空值:''(一個空字符串)
  • 規範化爲:一個Unicode 對象。
  • 驗證給定值是個有效的URL。
  • 錯誤信息的鍵:required, invalid

可選參數:max_length和min_length

23. UUIDField

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:UUID對象。
  • 錯誤信息的鍵:required, invalid

24. ComboField

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:Unicode 對象。
  • 根據指定爲ComboField的參數的每一個字段驗證給定值。
  • 錯誤信息的鍵:required, invalid

接收一個額外的必選參數:fields,用於驗證字段值的字段列表(按提供它們的順序)。

>>> from django.forms import ComboField >>> f = ComboField(fields=[CharField(max_length=20), EmailField()]) >>> f.clean('test@example.com') 'test@example.com' >>> f.clean('longemailaddress@example.com') Traceback (most recent call last): ... ValidationError: ['Ensure this value has at most 20 characters (it has 28).'] 

25. MultiValueField

  • 默認的Widget:TextInput
  • 空值:''(一個空字符串)
  • 規範化爲:子類的compress方法返回的類型。
  • 根據指定爲MultiValueField的參數的每一個字段驗證給定值。
  • 錯誤信息的鍵:incomplete, invalid, required

26. SplitDateTimeField

  • 默認的Widget:SplitDateTimeWidget
  • 空值:None
  • 規範化爲:Python datetime.datetime 對象。
  • 驗證給定的值是datetime.datetime或以特定日期時間格式格式化的字符串。
  • 錯誤信息的鍵:invalid_date, invalid, required, invalid_time

3、建立自定義字段

若是內置的Field真的不能知足你的需求,還能夠自定義Field。

只須要建立一個django.forms.Field的子類,並實現clean()和__init__()構造方法。__init__()構造方法須要接收前面提過的那些核心參數,好比widget、required,、label、help_text、initial。

還能夠經過覆蓋get_bound_field()方法來自定義訪問字段的方式。

相關文章
相關標籤/搜索