开发者

form index in inlineformset

开发者 https://www.devze.com 2023-02-20 03:59 出处:网络
I have a formset created using inlineformset_factory. It doesn\'t matter what it looks like to answer this开发者_StackOverflow中文版 question. In the template I am looping through it with for form in

I have a formset created using inlineformset_factory. It doesn't matter what it looks like to answer this开发者_StackOverflow中文版 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.


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.


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].

0

精彩评论

暂无评论...
验证码 换一张
取 消