Get type of Django form widget from within template
Following up on the accepted answer - the enhanced if tag
in Django 1.2 allows you to use filters in if tag
comparisons. So you could now do your custom html/logic in the template like so:
<ul>
{% for field in form.fields %}
<li>
{% if field.field.widget|klass == "Textarea" %}
<!-- do something special for Textarea -->
<h2>Text Areas are Special </h2>
{% else %}
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% endif %}
</li>
{% endfor %}
</ul>
As of Django 1.11, you can just use widget.input_type
. Example:
{% for field in form.visible_fields %}
<input type="{{ field.field.widget.input_type }}"
id="{{ field.id_for_label }}"
name="{{ field.html_name }}"
placeholder="{{ field.label }}"
maxlength="{{ field.field.max_length }}" />
{% endfor %}
Making a template tag might work? Something like field.field.widget|widget_type
Edit from Oli: Good point! I just wrote a filter:
from django import template
register = template.Library()
@register.filter('klass')
def klass(ob):
return ob.__class__.__name__
And now {{ object|klass }}
renders correctly. Now I've just got to figure out how to use that inside a template's if
statement.
Edit from Oli #2: I needed to use the result of that in an if statetement in-template, so I just shifted all that logic into the templatetag. Magic. Thanks for poking me in the right direction.