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
{{ form.as_p }} – Render Django Forms as paragraph. {{ form.as_ul }} – Render Django Forms as list.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With