如何在Django的CharField中添加占位符? [英] How do I add a placeholder on a CharField in Django?
问题描述
以这个非常简单的形式为例。
Take this very simple form for example.
class SearchForm(Form):
q = forms.CharField(label='search')
在模板中呈现:
<input type="text" name="q" id="id_q" />
但是,我想将占位符属性添加到此字段中,值为搜索所以HTML将看起来像:
However, I want to add the 'placeholder' attribute to this field with a value of "Search" so that the HTML would look something like:
<input type="text" name="q" id="id_q" placeholder="Search" />
最好我想通过一个字典或一些东西将占位符值传递给表单类的CharField如:
Preferably I would like to pass the placeholder value in to CharField in the form class through a dictionary or something like:
q = forms.CharField(label='search', placeholder='Search')
什么是最好的方法来完成这个?
What would be the best way to accomplish this?
推荐答案
查看小部件文档。基本上它看起来像:
Look at the widgets documentation. Basically it would look like:
q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
更多的写作,是的,但是分离可以更好地抽象出更复杂的情况。
More writing, yes, but the separation allows for better abstraction of more complicated cases.
您还可以声明一个小部件
属性,其中包含一个<字段名称> => < widget instance>
直接在 ModelForm
子类的 Meta
上映射。
You can also declare a widgets
attribute containing a <field name> => <widget instance>
mapping directly on the Meta
of your ModelForm
sub-class.
这篇关于如何在Django的CharField中添加占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!