Django:从模板中获取表单名称或 id [英] Django: Get the form name or id from template
问题描述
如果你有多个表单
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
class SecondNameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
有没有办法在你的模板中找出context
里面的form
是属于NameForm
还是SecondNameForm
is there a way that, in your template, you can figure out if form
in inside context
belongs to NameForm
or SecondNameForm
我有一个自定义小部件,在其 html 中,它使用 id=""
标识符(在整个 html 中应该是唯一的).
I have a custom widget that in its html, it uses the id=""
identifier (which should be unique in the whole html).
我想将 id 分配给类似
I want to assign the id to something like
id="{{form.name}}_{{field.val}}"
或id="{{form.id}}_{{field.val}}"
或
其中 {{form.name}}
和 {{form.id}}
是一些与表单实例相关的值,而不是表单的内容.
where {{form.name}}
and {{form.id}}
is some value associated with the form instance and not the form's content.
推荐答案
如果您使用独特的 prefix
对于每个表单,那么这些字段都将具有唯一的 ID.
If you use a unique prefix
for each form, then the fields will all have unique ids.
form1 = NameForm(prefix='name')
form2 = SecondNameForm(prefix='second_name')
这篇关于Django:从模板中获取表单名称或 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!