内联表单集中的表单索引
我有一个使用 inlineformset_factory
创建的 formset
。回答这个问题的样子并不重要。在模板中,我使用 for form in forms.formset:
循环遍历它,
我希望能够在模板中显示表单的表单索引。通过表单索引,我的意思是所有表单字段中与该表单关联的数字。有没有一个变量可以做到这一点?我尝试了 form.index
和 form.form_id
,并且 form.id
是一个字段。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,集合中的对象通常无法访问其索引或键。
但是,如果您在模板中输出表单集,则可能会循环遍历表单。所以你可以使用
{% forloop.counter %}
来获取迭代的索引。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.虽然它并不漂亮,但基于 formset source 和上面 @yuji-tomita-tomita 的评论,你可以在模板中执行类似的操作:
{{ form.prefix|cut:formset.prefix|cut:'-' } }
这仅采用表单前缀字符串,其中包括表单索引,然后删除不相关的部分。在视图中,您可以简单地执行例如
form.prefix.split('-')[1]
。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]
.