Widgets怎么在django表单中使用

发布时间:2021-03-24 16:19:13 作者:Leah
来源:亿速云 阅读:175

今天就跟大家聊聊有关Widgets怎么在django表单中使用,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

一、指定使用的widget

每个字段都有一个默认的widget类型。如果你想要使用一个不同的Widget,可以在定义字段时使用widget参数。 像这样:

from django import forms

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

这将使用一个Textarea Widget来展现表单的评论字段,而不是默认的TextInput Widget。

二、设置widget的参数

许多widget具有可选的额外参数,下面的示例中,设置了SelectDateWidget的years 属性,注意参数的传递方法:

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样式

默认情况下,当Django渲染Widget为实际的HTML代码时,不会帮你添加任何的CSS样式,也就是说网页上所有的TextInput元素的外观是一样的。

看下面的表单:

from django import forms

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

这个表单包含三个默认的TextInput Widget,以默认的方式渲染,没有CSS类、没有额外的属性。每个Widget的输入框将渲染得一模一样,丑陋又单调:

>>> 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>

在真正的网页中,你可ending不想让每个Widget看上去都一样。可能想要给comment一个更大的输入框,可能想让‘name' Widget具有一些特殊的CSS类。

可以在创建Widget时使用Widget.attrs参数来实现这一目的:

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'}))

注意参数的传递方式!

这次渲染后的结果就不一样了:

>>> 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>

看完上述内容,你们对Widgets怎么在django表单中使用有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

推荐阅读:
  1. Flutter Widgets中ListWheelScrollView的用法
  2. django-表单

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

django widgets

上一篇:如何在Django中使用 Django-debug-toolbar调试工具

下一篇:如何正确的使用Bootstrap、Dual和Listbox插件

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》