Html Django:在模板中选择选项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8389880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django: Select option in template
提问by Nava
In my Django template, I am using the list of objects in a drop down menu. I am processing it based on the selection.
在我的 Django 模板中,我使用下拉菜单中的对象列表。我正在根据选择处理它。
The HTML Template:
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>
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
问题是当我从下拉菜单中选择值时,我得到了属于选择的内容。由于属性selected="selected"只修复了"---SELECT---"元素,除非我把selected="selected"放在
<option value="{{org.id}}" selected="selected">{{org.name|capfirst}}</option>
In these organisation, the last iterated elementis 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?
我该如何解决这个问题?
回答by Dan Breen
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:
您可能希望将当前选定的组织传递到视图中,current_org
以便在您遍历组织时可以与当前组织进行比较以确定是否选择它,例如:
{% for org in organisation %}
<option value="{{org.id}}"
{% if org == current_org %}selected="selected"{% endif %}>
{{org.name|capfirst}}
</option>
{% endfor %}