[Django]-Custom formset templates in Django

2πŸ‘

βœ…

In your template, you have two <tr> elements, each of which contains a loop over form.visible_fields, each iteration of which generates a single <th> or <td>.

Change this round so that you have a single loop over form.visible_fields, each iteration of which contains a single <tr> element containing a <th> and a <td>. Like this:

<table id="formset" class="form">
{% for form in formset.forms %}
  {% for field in form.visible_fields %}
  <tr class="{% cycle row1,row2 %}">
    <th>{{ field.label|capfirst }}</th>
    <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>
  </tr>
  {% endfor %}
{% endfor %}    
</table>
πŸ‘€Gareth Rees

2πŸ‘

The examples above seem to show a column-wise layout, which appears to be the default layout when a formset renders itself.

To make it row-wise, use something like this:

<table>
    {% for form in formset.forms %}
        {% if forloop.first %}
            <thead>
                {% for field in form.visible_fields %}
                    <th>{{ field.label }}</th>
                {% endfor %}    
            </thead>
            <tbody>
        {% endif %}

        <tr class="{% cycle row1,row2 %}">                        
            {% for field in form.visible_fields %}
                <td>
                    {% if forloop.first %}
                        {% for hidden in form.hidden_fields %}
                            {{ hidden }}
                        {% endfor %}
                    {% endif %}

                    {{ field.errors.as_ul }}
                    {{ field }}
                </td>
            {% endfor %}
        </tr>
        {% if forloop.last %}
            </tbody>
        {% endif %}
    {% endfor %}    
</table>

Leave a comment