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