Django template, how to make a dropdown box with the predefined value selected?


Question

I am trying to create a drop down list box with the selected value equal to a value passed from the template values, but with no success. Can anyone take a look and show me what I am doing wrong.

     <select name="movie">
       {% for movie in movies %}
    {% ifequal movie.id selected_movie.id %}
     <option value="{{movie.key}}" selected="true">Movie {{movie.id}}: {{movie.name}}</option>
     {% endifequal %}
     {% ifnotequal movie.id selected_movie.id %}
     <option value="{{movie.key}}">Movie {{movie.id}}: {{movie.name}}</option>
     {% endifnotequal %}
       {% endfor %}
     </select>

In this example, movies and selected_movie are passed from the template values. Please advice!

1
6
9/8/2009 9:54:17 AM

Accepted Answer

Your code works for me with django 1.0.2 and firefox 3.5.

You can use {% else %} instead of {% ifnotequal %} and set selected="selected". Hope it helps.

<select name="movie">
    {% for movie in movies %}
        {% ifequal movie.id selected_movie.id %}
            <option value="{{movie.key}}" selected="selected">Movie {{movie.id}}: {{movie.name}}</option>
        {% else %}
            <option value="{{movie.key}}">Movie {{movie.id}}: {{movie.name}}</option>
        {% endifequal %}
    {% endfor %}
</select>
12
11/23/2010 8:46:12 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon