How to access django form field name in template

I have a model that I would like to iterate through the form fields in the template, but at the same time, when I encounter certain fields, conditionally display additional html. I'm currently pulling a field name from field.html_name , but I'm not sure if this is the best way (it somehow seems hacked, as if I should use the getattr() filter or something else ...).

 {% for field in form %} <div class="form-group"> {{ field }} {% if field.html_name == "location" %} <!-- CUSTOM HTML HERE --> {% endif %} </div> {% endfor %} 
+5
source share
3 answers

I have the same situation if I misunderstand your meaning. My solution is field.name . Code example:

 {% if field.name == 'password' %} <input type="password" name="password" class="form-control" placeholder="{% trans 'Enter your password' %}"> {% else %} <input type="email" name="email" class="form-control" placeholder="{% trans 'Enter your email address' %}"> {% endif %} 
+5
source

Do you consider using a widget or creating your own custom widget? https://docs.djangoproject.com/en/1.10/ref/forms/widgets/

For example: to add only the css class or similar existing input, use the attrs argument

 class MyForm(forms.Form): ... location = forms.CharField( ..., widget=Input(attrs={'class': 'location', 'style': 'background: red'}), ) ... 

Or create a complete custom widget (see how Login is implemented)

 class LocationFieldWidget(Widget): def render(self, name, value, attrs=None): return mark_safe('custom html') 

and then the form can be displayed in the template simply

  {{ form }} 
+1
source

I don’t know how you mean, but you can try this

 {% for field in form %} {{ field }} {% if field.label == 'Location' %} <h1>Hi</h1> {% endif %} {% endfor %} 

While you set the label in forms.py as

 location = forms.CharField(widget=forms.TextInput( attrs={'class': 'yourclass', 'placeholder': 'Enter your location', }), label=u'Location', max_length=100, required=True) 
+1
source

All Articles