I’m making a html form using Django Forms. I use BoundFields because my form layout has some special things in it.
I have a ChoicesField with a RadioSelect widget in my form. I iterate manually over the the choices because I want to put an img inside the <li>:
<ul>
{% for country in form.country %}
<li>
<img src="{{ MEDIA_URL }}country_icons/country_{{ country.value }}.png">
{{ country }}
</li>
{% endfor %}
</ul>
But now the output doesn’t include id tags on the input elements:
<ul>
<li>
<img src="/media/country_icons/country_nl.png">
<label>
<input type="radio" value="nl" name="country" checked="checked">
Netherlands
</label>
</li>
<li>
<img src="/media/country_icons/country_de.png">
<label>
<input type="radio" value="de" name="country">
Germany
</label>
</li>
</ul>
While, when I wouldn’t iterate over the options and just output the field:
{{ form.country }}
will output:
<ul>
<li>
<label for="id_country_0">
<input id="id_country_0" type="radio" value="nl" name="country" checked="checked">
Netherlands
</label>
</li>
<li>
<label for="id_country_1">
<input id="id_country_1" type="radio" value="de" name="country">
Germany
</label>
</li>
</ul>
So my problem is that the id field is not there when I manually iterate over the choices. This makes inconsistency in my css/javascript selectors.
So my question is, is there some way to include the id-tag anyway?
Is this behaviour intended anyway? Or might this be a bug? Anyone run into a similar kind of issue?
I don’t know why it works like that. My guess would be that those id’s are created by an iterator created by the forms api. A single country is not aware of the iterator (it could appear in the template without appearing within a for loop), therefor there’s no way of creating the id.
To answer your other question – Yes you could build the inputs yourself to include the id’s.
something like –
Have a look at the docs on template for loops