如何在表单中插入额外的内容?

时间:2011-08-18 12:32:42

标签: django django-forms

我有表格:

class ItemForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=Item.objects.all(), widget=forms.HiddenInput())
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc

在模板中我有:

    {% for field in itemForm %}
        {% if field.is_hidden %}
            {{ field }}
        {% else %}
            <div class="fieldWrapper">
                 {% if field.errors %}<div class="errorbox">{% endif %}
                    <p>{{ field.label_tag }}</p>
                    <p>{{ field }}</p>
                    <p></p>
                {% if field.errors %}<p>{{ field.errors }}</p></div>{% endif %}
            </div>
        {% endif %}
    {% endfor %}

它是不同形式的通用模板。现在以一种形式:

class DifferentForm(forms.ModelForm):
    id = forms.ModelChoiceField(queryset=DifferentItem.objects.all(), widget=forms.HiddenInput())
    option = forms.ModelChoiceField(queryset=Option.objects.all(), widget=forms.HiddenInput())
    (????)
    temp = forms.BooleanField(widget=forms.HiddenInput(), required=False)
    date = forms.SplitDateTimeField(widget=forms.SplitDateTimeWidget())
    ... etc

我希望以这种方式展示一个额外的链接:

<select ...>
    <option>...</option>
</select>
(my additional link, button, text, whatever)
<input ...

怎么做?

1 个答案:

答案 0 :(得分:1)

我通常这样做的方式是在模板中:

{% for field in itemForm %}
    {% if field.name == "option" %}
       Custom stuff I want to go before this field
    {% endif %}

    <!-- Regular field stuff goes here -->
    {% if field.is_hidden %}
        {{ field }}
    {% else %}
        <div class="fieldWrapper">
            ...
        </div>
    {% endif %}
    <!-- End Regular Field Stuff -->

    {% if field.name == "option" %}
       Custom stuff I want to go after the field
    {% endif %}
    {% if field.name == "another_field_name"%}
       Custom stuff I want to go after the field
    {% endif %}
{% endfor %}