[Django]-Django – Adding a custom title to forms in a formset

4👍

You can put a label in template using forloop.counter before each form, something as below

<form method="post" action="">
    {{ formset.management_form }}
    <table>
        {% for form in formset %}
        <label> Form - {{forloop.counter}} </label>
        {{ form }}
        {% endfor %}
    </table>
</form>
👤Rohan

1👍

I realized the docs give the solution. You can access {{forloop.counter}} in the Layout and create a label using the HTML universal layout element:

Note that you can still use a helper (in this case we are using the
helper of the form used for building the formset). The main difference
here is that helper attributes are applied to the form structure,
while the layout is applied to the formset’s forms. Rendering formsets
injects some extra context in the layout rendering so that you can do
things like:

HTML(“{% if forloop.first %}Message displayed only in the first form
of a formset forms list{% endif %}”, Fieldset(“Item {{ forloop.counter
}}”, ‘field-1’, […])

👤Neil

Leave a comment