Neil
Neil

Reputation: 7202

django - Adding a custom title to forms in a formset

I am using a formset and I want each from generated to display a numbered title for each unique form. So if I generate 5 forms, I want to have a text label display before the form fields that says "Form 1", "Form 2", ... "Form 5".

How do I:

  1. Create a space in a form for such a plain informational text label?
  2. Set the title for each form (I'm assuming in the template)?

Thanks!

Upvotes: 3

Views: 1706

Answers (2)

Neil
Neil

Reputation: 7202

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', [...])

Upvotes: 1

Rohan
Rohan

Reputation: 53316

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>

Upvotes: 4

Related Questions