修改Django ModelForm的HTML输出

时间:2012-11-09 14:10:14

标签: django django-forms

默认情况下,我的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输出的任何想法吗?

2 个答案:

答案 0 :(得分:1)

您需要导入小部件from 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..."}),
        }

答案 1 :(得分:1)

您只忘了from django.forms.widgets import Select