0

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

4

2 回答 2

1

您需要django.forms以下位置导入小部件:

from django import forms
class FoodForm(forms.ModelForm):
    class Meta:
        model = Food
        fields = ('name', 'ingredients')
        widgets = {
            'ingredients': forms.Select(attrs={'data-placeholder': "Choose ingredients..."}),
        }
于 2012-11-09T14:20:45.140 回答
1

你只是忘了from django.forms.widgets import Select

于 2012-11-09T14:21:44.233 回答