Reputation: 1892
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.
Upvotes: 1
Views: 5271
Reputation: 3659
If you are working with forms you can get the id from the templates
{{ form.instance.pk ]}
Upvotes: 0
Reputation: 308779
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')
Upvotes: 2
Reputation: 53734
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}}"
Upvotes: 1