Django表單欄位彙總
阿新 • • 發佈:2018-12-30
Field.clean(value)[source]
雖然表單欄位的Field類主要使用在Form類中,但也可以直接例項化它們來使用,以便更好地瞭解它們是如何工作的。每個Field的例項都有一個clean()方法,它接受一個引數,然後返回“清潔的”資料或者丟擲一個django.forms.ValidationError
異常:
>>> from django import forms
>>> f = forms.EmailField() >>> f.clean('[email protected]') '[email protected] ' >>> f.clean('invalid email address') Traceback (most recent call last): ... ValidationError: ['Enter a valid email address.']
這個clean方法經常被我們用來在開發或測試過程中對資料進行驗證和測試。
一、核心欄位引數
以下的引數是每個Field類都可以使用的。
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:
>>> 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引數的值,如下所示:
>>> 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頁面將包含驗證中產生的錯誤,如下所示:
>>> 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=