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

查看:30
本文介绍了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)

有没有办法在你的模板中找出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屋!

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