Django: Get the form name or id from template

醉酒当歌 提交于 2019-12-20 04:09:31

问题


If you have multiple forms

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)

is there a way that, in your template, you can figure out if form in inside context belongs to NameForm or SecondNameForm

I have a custom widget that in its html, it uses the id="" identifier (which should be unique in the whole html).

I want to assign the id to something like

id="{{form.name}}_{{field.val}}" or id="{{form.id}}_{{field.val}}" or

where {{form.name}} and {{form.id}} is some value associated with the form instance and not the form's content.


回答1:


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') 



回答2:


In your view, you can do form.__class__.__name__ but this doesn't work inside a template because django templates do not recognize variables that begin with __

The best thing to do in your case would be to simply create an extra context variable that identifies the form name

id="{{form_name}}_{{field.val}}"



回答3:


If you are working with forms you can get the id from the templates

{{ form.instance.pk ]}



来源:https://stackoverflow.com/questions/40494064/django-get-the-form-name-or-id-from-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!