2017-09-21 22 views
1

我有一個inlineformsetCreateView存儲相關的模型記錄。Django中我使用<code>Django 1.11</code></p> <p>手動渲染表單域,而不是form.as_p

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手動渲染字段以及錯誤字段和隱藏字段?

回答

2

你可以看看Django文檔Rendering fields manually

+0

這將工作的優良'business'模型是父模型。如何呈現'business_address'字段的字段?因爲這是'inlineformset'。 –

+0

我試着用'business_address.line_1.label'但是沒有打印 –

+0

用'{{business_address.form.line_1.label}}' –

相關問題