A.Pie
A.Pie

Reputation: 1

Django forms ChoiceField. My select don't show options

I just start learn Django but I can't find any simple example without using database. I found one, but when I tried do this same on my project...this just don't work. I need help because now I have no idea what's wrong.

forms.py

MY_CHOICES = (
('1', 'Option 1'),
('2', 'Option 2'),
('3', 'Option 3'),
)

class MyTestForm(forms.Form):
  my_choice_field = forms.ChoiceField(choices=MY_CHOICES)

views.py

def my_view(request):
    form = MyTestForm()
    return render_response('/home/.../test.html',{'form': form})

test.html

<div>
    <select>
    {% for choice in form.my_choice_field %}
        <option>{{choice.1}}</option>

    </select>
    {% endfor %}

</div>

And this just show empty drop-down list. Thanks for any help!

Upvotes: 0

Views: 1738

Answers (2)

Sardorbek Imomaliev
Sardorbek Imomaliev

Reputation: 15400

It should be form.my_choice_field.choices not form.my_choice_field

<div>
    <select>
    {% for choice in form.fields.my_choice_field.choices %}
        <option>{{choice.1}}</option>
    {% endfor %}    
    </select>
</div>

Upvotes: 3

Alasdair
Alasdair

Reputation: 309089

The easiest approach is to use {{ form.my_choice_field }}, and let Django take care of rendering the choice field for you.

If you really need to render the field manually, you can access the choices via the bound field's field attribute.

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

I wasn't able to find a reference for this in the docs, so I don't know whether or not it's a documented API.

Upvotes: 1

Related Questions