I want to add extra infos for some fields of a django form, and use it in templates to add some extra html tags
I've a django form like:
class MyForm(forms.Form):
integer = forms.IntegerField(
help_text='Please enter your favorite integer number',
label='Favorite integer',
widget=forms.TextInput(attrs={'class':'input-xlarge'}))
decimal = forms.DecimalField(
min_value=Decimal('0.0001'),
decimal_places=4,
help_text='Please enter your favorite decimal number',
label='Favorite decimal',
widget=forms.TextInput(attrs={'class':'input-xlarge'}))
==> here I would like to say: decimal will have a new property
I am rendering MyForm in a template, using a loop over each field:
{% for item in form.visible_fields %}
==> here I would like to test if item has that property to add some html tags
{{ item }}
{% endfor %}
I cannot use the widget's attrs, as I want to use the property info outside the rendered input tag.
Should I create a custom field, write custom renderers for all fields I use, or is there a simpler solution I did miss ?
Edit: So far my solution is : (simplified version) Main template:
<form action="/somewhere/" method="post">{% csrf_token %}
{% include 'form_field.html' with item=form.integer icon="icon-home" %}
{% include 'form_field.html' with item=form.decimal icon="icon-list-alt" %}
{% include 'form_field.html' with item=form.another icon="icon-signal" %}
{% include 'form_field.html' with item=form.again icon="icon-time" %}
...
In form_field.html, I render a field using Twitter's Bootstrap input-prepend div:
<div class="control-group">
<label class="control-label" for="{{ item.name }}">{{ item.label }}</label>
<div class="controls">
{% if icon %}
<div class="input-prepend">
<span class="add-on"><i class="{{ icon }}"></i></span>
{% endif %}
{{ item }}
<p class="help-block">{{ item.help_text }}</p>
{% if icon %}
</div>
{% endif %}
</div>
</div>
All I want is to simplify the main template, using a loop rather enumerating all fields, which is error prone. So I want to move that 'icon-home' property from the template to the form definition, to have all attributes in the same place (specific widget attrs are already in the form). Ideally, in the main template I would have:
{% for item in form.visible_fields %}
{% include 'form_field.html' %}
{% endfor %}
I understand it can be viewed as a misunderstanding of Django's principles (site look should be in templates, not in forms)...