Reputation: 299
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
Upvotes: 6
Views: 6906
Reputation: 1135
If you want to render manually a choicefield and have it correctly rendered with the right selected choice, you'd better use the subwidgets
attribute instead. In this case, it's not totally manually done, though !
<select name="{{ form_bonus.select_product.name }}">
{% for widget in form_bonus.select_product.subwidgets %}
{{ widget }}
{% endfor %}
</select>
Upvotes: 1
Reputation: 2675
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.
Upvotes: 16