在Django模板的下拉列表中显示已选择的项目

问题描述 投票:0回答:1

嗨,我有一个这样的下拉列表

           <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>

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

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个选项,则它将打印两次选项,但选择的结果正确。任何帮助将不胜感激,谢谢。

django django-templates multi-select
1个回答
0
投票

如果categories是要选择的类别的列表,则可以将其设为列表(category_names = [category.category for category in categories]),并且在HTML中,不要迭代categories(这会导致N类别),而是检查每个选项是否在所选列表中:

<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>
© www.soinside.com 2019 - 2024. All rights reserved.