Django:从模板获取表单名称或ID [英] Django: Get the form name or id from template

查看:408
本文介绍了Django:从模板获取表单名称或ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有多个表单

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆