Django: Get the form name or id from template

前端 未结 3 1719
星月不相逢
星月不相逢 2021-01-24 12:21

If you have multiple forms

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label=\'Your name\', max_length=100)

class Sec         


        
相关标签:
3条回答
  • 2021-01-24 12:58

    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') 
    
    0 讨论(0)
  • 2021-01-24 13:08

    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}}"
    
    0 讨论(0)
  • 2021-01-24 13:08

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

    {{ form.instance.pk ]}

    0 讨论(0)
提交回复
热议问题