Django: Select option in template
Asked Answered
S

2

33

In my Django template, I am using the list of objects in a drop down menu. I am processing it based on the selection.

The HTML Template:

<select id="org" name="org_list" onChange="redirectUrl()">
  <option  value="" selected="selected">---SELECT---</option>
  {% for org in organisation %}
   <option value="{{org.id}}">{{org.name|capfirst}}</option>
  {% endfor %}
</select>

The problem is that when I am selecting the value from the drop down menu, I am getting the contents which belong to the selection. Since the attribute selected="selected" which only fixes to the "---SELECT---" element, unless I put the selected="selected" in

<option value="{{org.id}}" selected="selected">{{org.name|capfirst}}</option>

In these organisation, the last iterated element is only being fixed with drop down. But I want the selected element to be displayed in the drop down menu.

How can I solve this issue?

Soppy answered 5/12, 2011 at 18:15 Comment(0)
I
61

You'll want to pass the currently selected org into the view, maybe as current_org so that when you're iterating through the orgs you can compare with the current one to determine whether or not to select it, like:

{% for org in organisation %}
   <option value="{{org.id}}"
       {% if org == current_org %}selected="selected"{% endif %}>
       {{org.name|capfirst}}
   </option>
{% endfor %}
Inquisitionist answered 5/12, 2011 at 18:26 Comment(0)
E
0

Recently I have found a better approach to this problem which I shared on django forum Reiterating it here again:

{% for option in form.form_field.subwidgets %}
<option value="{{ option.data.value }}" {{option.data.attrs.selected|safe|yesno:"selected,"}}> {{ option.choice_label }} </option>
{% endfor %}
Elinorelinore answered 24/5 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.