如何在 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" />
但是,我想将 placeholder
属性添加到该字段,其值为 Search
,以便 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?
推荐答案
查看 widgets 文档.基本上它看起来像:
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.
您还可以声明包含
直接映射到 widgets
属性;=><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屋!