djangodjango-widget

How to render Form Choices manually


I have in form.py

SELECT_PRODUCT = [
    ('item1', 'item1'),
    ('item2', 'item2'),
    ('item3', 'item3'),
    ('item4', 'item4'),
]

class OrderBonus(forms.Form):
    select_product = forms.CharField(widget=forms.Select(choices=SELECT_PRODUCT ))

in html i need to render each choice individually:

<select name="{{ form_bonus.select_product .name }}">
    <option value="{{form_bonus.select_product.field.choice.0}}">{{form_bonus.select_product.field.choice.0}}</option>
    <option value="{{form_bonus.select_product.field.choice.1}}">{{form_bonus.select_product.field.choice.1}}</option>
    <option value="{{form_bonus.select_product.field.choice.2}}">{{form_bonus.select_product.field.choice.2}}</option>
 </select>

I try different ways: 1) form_bonus.select_product.field.choice.0 2) form_bonus.select_product.field.choice.[0] 3) form_bonus.select_product.field.choice.("0")

I try iteration:

{% for choice in form_bonus.select_product.field.choices %}
    {{ choice }}
{% endfor %}

or

{% for value, text in form_bonus.select_product.field.choices %}
    {{ value}} - {{ text }}
{% endfor %}

Anyone know how maybe overwrite the Select Widget to use each choice: form_bonus.select_product.field.choice.0 ect.

Python 3.5.2 and Django 1.10


Solution

  • Try this:

    <select name="{{ form_bonus.select_product.name }}">
        {% for choice in form_bonus.select_product.field.choices %}
            <option value="{{ choice.0 }}">{{ choice.1 }}</option>
        {% endfor %}
    </select>
    

    But make sure to use ChoiceField instead of CharField:

    class OrderBonus(forms.Form):
        select_product = forms.ChoiceField(choices=SELECT_PRODUCT)
    

    You could simply write {{ form_bonus.as_p }} instead of loop if you want.