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

Deadly 提交于 2019-12-21 01:24:26

问题


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:


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>


来源:https://stackoverflow.com/questions/1392706/django-template-how-to-make-a-dropdown-box-with-the-predefined-value-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!