Django:在模板中选择选项 [英] Django: Select option in template
问题描述
在我的Django模板中,我在下拉菜单中使用对象列表。我正在根据选择进行处理。
In my Django template, I am using the list of objects in a drop down menu. I am processing it based on the selection.
HTML模板:
<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>
问题是当我从下拉菜单中选择值时,我收到了内容属于选择。由于属性 selected =selected,它仅修复--- SELECT ---元素,除非我将 selected =selected
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>
在这些组织中,最后一个迭代元素只能用drop下。但是我想要选择的元素显示在下拉菜单中。
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.
我如何解决这个问题?
推荐答案
您将要将当前选定的组织传递到视图中,也许是 current_org
,以便您在迭代时您可以与当前的组织进行比较,以确定是否选择它,如:
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 %}
这篇关于Django:在模板中选择选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!