[Django]-Setting ID for Radio buttons in Django

6👍

While debuging a RadioSelect rendering, I got no idea of using radio tag and label elegantly. So here is my attempt to solve your problem:

{% for radio in form.important_client reversed %}
    <input name="{{ radio.name }}" type="radio" id="radio_{{ radio.index }}" value={{ radio.choice_value }}>
    <label for="radio_{{ radio.index }}">{{ radio.choice_label }}</label>
{% endfor %}

Instead of radio.index property, which is not documented, you can use forloop.counter.

Just in case I attach a screenshot of debug window, where example of radio context is shown (form_of_field variable on a figure):
radio select debug

2👍

This is one way to do that, it might not be the best but it works. In your form you can set the id for each of the choices like this:

from django import forms
class MyForm(forms.Form):
    CHOICES = (('1','Available'),('2','Not Available'))
    input   = forms.ChoiceField(widget=RadioSelect(attrs={'id' : 'myId'},choices=CHOICES)

Then on your template:

{% for radio in form.input %}
    {{ radio }}
{% endfor %}

And your HTML will look like this:

<label for="myId_0"><input id="myId_0" name="input" type="radio" value="1"></label> Available
<label for="myId_0"><input id="myId_0" name="input" type="radio" value="2"></label> Not Available

I hope this works!

Leave a comment