Show already selected item in dropdown in django template

橙三吉。 提交于 2019-12-24 18:46:34

问题


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)

when I for loop like this

 {% 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 %}

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.


回答1:


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>

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.



来源:https://stackoverflow.com/questions/59313031/show-already-selected-item-in-dropdown-in-django-template

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