Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 268
gamer Avatar asked Oct 23 '25 18:10

gamer


1 Answers

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>
like image 126
Willem Van Onsem Avatar answered Oct 26 '25 08:10

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!