在Django模板的下拉列表中显示已选择的项目 [英] Show already selected item in dropdown in django template

查看:94
本文介绍了在Django模板的下拉列表中显示已选择的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似这样的下拉列表

Hi I have a dropdown like this

           <select name="category" data-placeholder="select Category here" multiple
                class="chosen-select" tabindex="8" required>
                <option value=""></option>
                <option>Transport</option>
                <option>Accommodation</option>
                <option>Ware House</option>
                <option>Readymade</option>
            </select>

我正在像这样从数据库过滤查询中获取此下拉列表的选定元素

And I am getting selected element of this dropdown from database Filter query like this

categories=Categories.objects.filter(vendor=uid)

当我进行这样的循环

 {% for category in categories %}
    <option value=""></option>
    <option value="{{ category.category }}"{% if category.category == 'Transport' %}selected{% endif %}>Transport</option>
    <option value="{{ category.category }}"{% if category.category == 'Accommodation' %}selected{% endif %}>Accommodation</option>
    <option value="{{ category.category }}"{% if category.category == 'Activity' %}selected{% endif %} >Activity</option>
   <option  value="{{ category.category }}"{% if category.category == 'Readymade' %}selected{% endif %}>Pre Packaged Plan</option>
                         </option>
                     {% endfor %}

在这种情况下,例如,如果我在数据库中选择了2个选项,则它将打印两次选项",但选择的结果是正确的.任何帮助将不胜感激.

In this case For example If I have 2 options selected in database then it prints Options two time but seleted result is correct. Any help would be highly appreciated thanks.

推荐答案

如果categories是您要选择的类别的列表,则可以将该列表(category_names = [category.category for category in categories])放在HTML中,请勿遍历categories(这将导致类别的N倍),而应检查每个选项是否在所选列表中:

If categories is a list of the categories you want to be selected, then you can make that a list (category_names = [category.category for category in categories]), and in your HTML, do not iterate over the categories (that would result in N times the categories), but rather check if each option was in the selected list:

<select ...>
    <option value=""></option>
    <option value="Transport" {% if 'Transport' in category_names %}selected{% endif %}>Transport</option>
    <option value="Accommodation" {% if 'Accommodation' in category_names %}selected{% endif %}>Accommodation</option>
    ...etc
</select>

现在,如果您需要动态地用类别名称填充此<select>,这是另一个问题,但这不是我解释这个问题的方式.

Now, if you need to populate this <select> with category names dynamically, that's another issue but it's not how I interpreted this question.

这篇关于在Django模板的下拉列表中显示已选择的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆