Can not iterate a ChoiceField with Select as widget

懵懂的女人 提交于 2019-12-10 17:06:32

问题


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)


回答1:


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. :)



来源:https://stackoverflow.com/questions/16117393/can-not-iterate-a-choicefield-with-select-as-widget

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!