Setting ID for Radio buttons in Django

后端 未结 2 1074
天涯浪人
天涯浪人 2021-01-21 03:06

It is great that Django 1.4 allows fine graining of radio select

{% for radio in form.important_client reversed%}
      {{radio.tag}}
相关标签:
2条回答
  • 2021-01-21 03:38

    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!

    0 讨论(0)
  • 2021-01-21 03:50

    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

    0 讨论(0)
提交回复
热议问题