默认情况下,我的 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 输出?