0
默認情況下,我的django ModelForm生成一個HTML表單。我想通過在select
元素的附加屬性修改窗體的HTML輸出:修改Django的HTML輸出ModelForm
# 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輸出?
謝謝,這工作。有沒有簡單的方法來添加新的屬性?當前的解決方案將使用小部件中指定的屬性替換所有屬性。我當然可以明確定義每個屬性,但有沒有更好的方法? – finspin