Reputation: 1540
I have a formset
created using inlineformset_factory
. It doesn't matter what it looks like to answer this question. In the template I am looping through it with for form in forms.formset:
I want to be able to display the form index of the form in my template. By form index, I mean the number associated with that form in all of the formfields. Is there a variable that does this? I tried form.index
and form.form_id
and form.id
is a field.
Upvotes: 1
Views: 229
Reputation: 14295
Although it is not pretty, based on the formset source and the comment by @yuji-tomita-tomita above, you could do something like this in your template:
{{ form.prefix|cut:formset.prefix|cut:'-' }}
This just takes the form prefix string, which includes the form index, then removes the irrelevant parts. In the view you could simply do e.g. form.prefix.split('-')[1]
.
Upvotes: 0
Reputation: 599788
No, objects in a collection don't generally have access to their index or key.
However if you're outputting the formset in a template, you're presumably looping through the forms. So you can use {% forloop.counter %}
to get the index of the iteration.
Upvotes: 2