【问题标题】:Django: Select option in templateDjango:在模板中选择选项
【发布时间】:2012-01-13 11:06:36
【问题描述】:

在我的 Django 模板中,我使用下拉菜单中的对象列表。我正在根据选择进行处理。

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"

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

在这些组织中,最后一次迭代的元素仅通过下拉固定。但我希望所选元素显示在下拉菜单中。

我该如何解决这个问题?

【问题讨论】:

  • 0 否决票 我可以查看models.py 或forms.py 吗?我想看看它是如何与模板链接的。谢谢。

标签: html drop-down-menu django-templates


【解决方案1】:

您需要将当前选定的组织传递到视图中,可能是current_org,这样当您遍历组织时,您可以与当前组织进行比较以确定是否选择它,例如:

{% for org in organisation %}
   <option value="{{org.id}}"
       {% if org == current_org %}selected="selected"{% endif %}>
       {{org.name|capfirst}}
   </option>
{% endfor %}

【讨论】:

    猜你喜欢
    • 2017-11-20
    • 2018-07-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2014-05-07
    • 2011-01-03
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多