Django手动渲染表单字段而不是form.as_p

时间:2017-09-21 07:11:12

标签: django django-forms django-templates django-1.11

我正在使用Django 1.11

我有CreateView inlineformset来存储相关的模型记录。

forms.py

class BusinessForm(ModelForm):
    class Meta:
        model = Business
        exclude = ()

BusinessAddressFormSet = inlineformset_factory(
    Business,
    BusinessAddress,
    form=BusinessForm,
    extra=1,
    can_delete=False
)

business_form.html,我正在做的是

<form method="post">
{% csrf_token %}
// render business form
{{ form.as_p }}

// render business address fields
{{ business_address.management_form }}
<table class="table">
    {{ business_address.management_form }}

    {% for form in business_address.forms %}
        {% if forloop.first %}
            <thead>
                <tr>
                    {% for field in form.visible_fields %}
                        <th>{{ field.label|capfirst }}</th>
                    {% endfor %}
                </tr>
            </thead>
        {% endif %}
        <tr class="{% cycle 'row1' 'row2' %} formset_row">
            {% for field in form.visible_fields %}
                <td>
                    {# Include the hidden fields in the form #}
                    {% if forloop.first %}
                       {% for hidden in form.hidden_fields %}
                           {{ hidden }}
                       {% endfor %}
                    {% endif %}
                    {{ field.errors.as_ul }}
                    {{ field }}
                </td>
            {% endfor %}
        </tr>
    {% endfor %}
</table>

这会将地址模型的所有字段呈现为

- line_1
- line_2
- city
- state
- postal

以上字段在table row中呈现。因为,我有一个单独的html模板用于不同字段的内联表单图标。

如何从business_address手动呈现字段以及错误字段和隐藏字段?

1 个答案:

答案 0 :(得分:2)

您可以查看django文档Rendering fields manually