I\'m iterating through the fields of a form and for certain fields I want a slightly different layout, requiring altered HTML.
To do this accurately, I just need to
Perhaps worth pointing out to contemporary readers that django-widget-tweaks provides field_type and widget_type template filters for this purpose, returning the respective class names in lowercase. In the example below I also show the output of the input_type property on the field widget (since Django 1.11), which may also be useful.
forms.py:
class ContactForm(forms.Form):
name = forms.CharField(
max_length=150,
required=True,
label='Your name'
)
template.html:
{% load widget_tweaks %}
{% for field in form.visible_fields %}
{{ field.label }}
{{ field.field.widget.input_type }}
{{ field|field_type }}
{{ field|widget_type }})
{% endfor %}
Result:
Your name
text
charfield
textinput
Between these various options you should be able to find the right property to target for just about any use-case. If you need to capture the output of one of these filters for use in if statements, you can use the with template tag.