Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 798
Hellbea Avatar asked Dec 08 '16 09:12

Hellbea


People also ask

What is form AS_P in Django?

{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.


1 Answers

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.

like image 159
Ivan Avatar answered Oct 08 '22 04:10

Ivan