溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Widgets怎么在django表單中使用

發(fā)布時(shí)間:2021-03-24 16:19:13 來源:億速云 閱讀:185 作者:Leah 欄目:開發(fā)技術(shù)

今天就跟大家聊聊有關(guān)Widgets怎么在django表單中使用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

一、指定使用的widget

每個(gè)字段都有一個(gè)默認(rèn)的widget類型。如果你想要使用一個(gè)不同的Widget,可以在定義字段時(shí)使用widget參數(shù)。 像這樣:

from django import forms

class CommentForm(forms.Form):
  name = forms.CharField()
  url = forms.URLField()
  comment = forms.CharField(widget=forms.Textarea)

這將使用一個(gè)Textarea Widget來展現(xiàn)表單的評論字段,而不是默認(rèn)的TextInput Widget。

二、設(shè)置widget的參數(shù)

許多widget具有可選的額外參數(shù),下面的示例中,設(shè)置了SelectDateWidget的years 屬性,注意參數(shù)的傳遞方法:

from django import forms

BIRTH_YEAR_CHOICES = ('1980', '1981', '1982')
FAVORITE_COLORS_CHOICES = (
  ('blue', 'Blue'),
  ('green', 'Green'),
  ('black', 'Black'),
)

class SimpleForm(forms.Form):
  birth_year = forms.DateField(widget=forms.SelectDateWidget(years=BIRTH_YEAR_CHOICES))
  favorite_colors = forms.MultipleChoiceField(
    required=False,
    widget=forms.CheckboxSelectMultiple,
    choices=FAVORITE_COLORS_CHOICES,
  )

三、為widget添加CSS樣式

默認(rèn)情況下,當(dāng)Django渲染W(wǎng)idget為實(shí)際的HTML代碼時(shí),不會幫你添加任何的CSS樣式,也就是說網(wǎng)頁上所有的TextInput元素的外觀是一樣的。

看下面的表單:

from django import forms

class CommentForm(forms.Form):
  name = forms.CharField()
  url = forms.URLField()
  comment = forms.CharField()

這個(gè)表單包含三個(gè)默認(rèn)的TextInput Widget,以默認(rèn)的方式渲染,沒有CSS類、沒有額外的屬性。每個(gè)Widget的輸入框?qū)秩镜靡荒R粯?,丑陋又單調(diào):

>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" required /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" required /></td></tr>

在真正的網(wǎng)頁中,你可ending不想讓每個(gè)Widget看上去都一樣??赡芟胍ocomment一個(gè)更大的輸入框,可能想讓‘name' Widget具有一些特殊的CSS類。

可以在創(chuàng)建Widget時(shí)使用Widget.attrs參數(shù)來實(shí)現(xiàn)這一目的:

class CommentForm(forms.Form):
  name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
  url = forms.URLField()
  comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))

注意參數(shù)的傳遞方式!

這次渲染后的結(jié)果就不一樣了:

>>> f = CommentForm(auto_id=False)
>>> f.as_table()
<tr><th>Name:</th><td><input type="text" name="name" class="special" required /></td></tr>
<tr><th>Url:</th><td><input type="url" name="url" required /></td></tr>
<tr><th>Comment:</th><td><input type="text" name="comment" size="40" required /></td></tr>

看完上述內(nèi)容,你們對Widgets怎么在django表單中使用有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI