gamer
gamer

Reputation: 613

How to set already selected value (Update form) in dynamic dropdown Django template

In django template I am showing dropdown like this . My all dropdown attribute names are in variable event_dropdown. And I am assigning like this code

<select  name="event_value" >
             <option value="">---------</option>
                 {% for event in event_dropdown %}
             <option value="{{ event.id }}">{{ event.name }}</option>
                  {% endfor %}
         </select>

Now Issue is In Update case How I can show my already selected value here ? As All things are in for loop

Upvotes: 4

Views: 2932

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476669

We can add the selected attribute to the value that is already selected, like:

<select  name="event_value" >
    <option value="">---------</option>
    {% for event in event_dropdown %}
    <option value="{{ event.id }}"{% if event.id == selected_id %}selected{% endif %}>
        {{ event.name }}
    </option>
    {% endfor %}
 </select>

Where selected_id is the id of the element.

In case there can be multiple selected ids, we can make a list or set of the selected_ids, and then work with:

<select  name="event_value" >
    <option value="">---------</option>
    {% for event in event_dropdown %}
    <option value="{{ event.id }}"{% if event.id in selected_ids %}selected{% endif %}>
        {{ event.name }}
    </option>
    {% endfor %}
 </select>

Upvotes: 5

Related Questions