Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Select Option selected issue

I tried to follow some examples on stackoverflow for option selected in select list but still, I could not get it work.

This is my code snippet

<select name="topic_id" style="width:90%">
    {% for t in topics %}
        <option value="{{t.id}}" {% if t.id == topic_id %} selected="selected" {% endif %}>{{t.title}}{{t.id}}</option>
    {% endfor %}
</select>

I took the topic_id from param['topic_id'] in views.py.

Thanks!

like image 870
jdtoh Avatar asked Dec 24 '12 12:12

jdtoh


2 Answers

Instead of selected="selected" just use selected.

<option value="{{t.id}}"{% if t.id == topic_id %} selected{% endif %}>{{t.title}}{{t.id}}</option>

There can be two reason if it is not working:

  • In topics there is no such topic whose id is equal to topic_id
  • t.id and topic_id may be of different types. Convert topic_id to int
like image 148
Aamir Rind Avatar answered Nov 20 '22 15:11

Aamir Rind


this worked for me

<select class="form-control" id="exampleSelect2" name="nivel">
                {% for key, value in types %}
                    <option value="{{ key }}" {% if institution.nivel == key %} selected {% endif %}>{{ value }}</option>
                {% endfor %}
</select>
like image 1
Diego Santa Cruz Mendezú Avatar answered Nov 20 '22 16:11

Diego Santa Cruz Mendezú