0

By default my django ModelForm generates an HTML form. I'd like to modify the HTML output of the form by including an extra attribute in the select element:

# 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>

I'd like to add a new attribute to the select field and leave the current attributes untouched:

# desired HTML output
<select multiple="multiple" name="ingredients" id="id_ingredients" data-placeholder="Choose ingredients...">

I tried to do it with widgets (see below) but it gives me an error:

class FoodForm(ModelForm):
    class Meta:
        model = Food
        fields = ('name', 'ingredients')
        widgets = {
            'ingredients': Select(attrs={'data-placeholder': "Choose ingredients..."}),
        }

# NameError: name 'Select' is not defined

Any ideas how to modify the HTML output?

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 に答える