Search code examples
djangochoicefield

Can not iterate a ChoiceField with Select as widget


I have issues with iterating over a ChoiceField and building my own HTML from the values and labels. When specifying "widget" parameter as Select, the field is not longer iterable.

However, it works fine if I specify it as RadioSelect.

The form:

class MyFormCreate( Form ) :
    QUOTES = (
            (34, "Hi, Patrick. Wait, I'M PATRICK!"),
            (21, "I like pie."), 
            (76, "No, this is Patrick!"),
    )
    patrick = ChoiceField(choices = QUOTES, widget = Select)

And the template:

<select name="{{form.patrick.name}}">
    {% for option in form.patrick %}
    <option value="{{option.choice_value}}">{{option.choice_label}}</option>
    {% endfor %}
</select>

What am I doing wrong?

(Python 2.7.3 and Django 1.4.5)


Solution

  • Would this be what you're looking for?

    <select name="{{ form.patrick.name }}">
        {% for value, text in form.patrick.field.choices %}
            <option value="{{ value }}">{{ text }}</option>
        {% endfor %}
    </select>
    

    Also, white space is your friend. :)