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)
有没有一种方法可以在您的模板中可以找出上下文
内的表单
是否属于 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分配给类似
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.
推荐答案
如果使用唯一的每个表单的前缀
,那么这些字段都将具有唯一的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屋!