<option {% if 'condition.' == 'condition....'%}selected{%endif%}> </option> not working in Django custom select

Viewed 2816

I am passing two objects 'editsub_obj' and 'cat' both key-value pairs to the template. The main aim is to keep option tag selected when name from both object list matches but the code is not working.

  <select class="form-control" id="" name="cat_name" required>
            {% if not editsub_obj %}

            {% for data in cat %}
                <option  value="{{data.id}}">{{data.category_name}}</option>
            {% endfor %}

            {% else %}

            {% for data in cat %}
                {% if editsub_obj.category_name == data.category_name %}
                <option   value="{{data.id}}" selected>{{data.category_name}}</option>
                {% else %}

                <option   value="{{data.id}}">{{data.category_name}}</option>

                {% endif %}

            {% endfor %}

            {% endif %}

   </select>

Expected :

selected should be selected with the category_name matches in both objects list.

Actual :

none of the options are showing as selected.

1 Answers

Your code can reduce to ::

    <select class="form-control" id="" name="cat_name" required>
        {% for data in cat %}
            <option value="{{data.id}}"
                {% if editsub_obj and editsub_obj.category_name in data.category_name %} 
                   selected
                {%endif%}>
                {{data.category_name}}
            </option>
        {% endfor %}
   </select>
Related