【发布时间】:2012-10-29 20:45:21
【问题描述】:
默认情况下,我的 django ModelForm 会生成一个 HTML 表单。我想通过在 select 元素中包含一个额外的属性来修改表单的 HTML 输出:
# models.py
class FoodForm(ModelForm):
class Meta:
model = Food
fields = ('name', 'ingredients')
# default HTML output
<form action="/" method="post">
<p>
<label for="id_name">Name:</label>
<input id="id_name" type="text" name="name" maxlength="30" />
</p>
<p>
<label for="id_ingredients">Ingredients:</label>
<select multiple="multiple" name="ingredients" id="id_ingredients">
<option value="1">Mozzarella</option>
<option value="2">Cottage cheese</option>
<option value="3">Onion</option>
我想添加一个新属性到选择字段并保持当前属性不变:
# desired HTML output
<select multiple="multiple" name="ingredients" id="id_ingredients" data-placeholder="Choose ingredients...">
我尝试使用小部件(见下文)但它给了我一个错误:
class FoodForm(ModelForm):
class Meta:
model = Food
fields = ('name', 'ingredients')
widgets = {
'ingredients': Select(attrs={'data-placeholder': "Choose ingredients..."}),
}
# NameError: name 'Select' is not defined
任何想法如何修改 HTML 输出?
【问题讨论】:
标签: django django-forms