0

在我正在处理的项目中,我需要默认情况下将select标签放在特定位置option。我试图做到这一点,如果我将变量设置为某个数字,则在页面加载时将选择相应的选项。出于某种原因,我用来判断选项是否与变量相同的代码总是返回 false。

视图.py

@login_required
def display_work(request, id, chapter = 1):
    info = dict()
    work = Work.objects.get(id = id)
    chapters = Chapter.objects.filter(work = id).order_by("order_number")
    info['title'] = work.title
    info['summery'] = work.summery
    info['current_chapter'] = chapter # the number the options are compared to
    print chapter
    info['id'] = id
    num_chapters = 0
    chapter_list = []
    for c in chapters:
        temp = (c.title, c.order_number) # where the numbering for the options is set (see template code)
        chapter_list.append(temp)
        num_chapters += 1
    info['total_chapter'] = num_chapters
    content = chapters[int(chapter)-1].content
    return render_to_response("SubMain/display_work.html", {'STATIC_URL':STATIC_URL, "info":info, "chapters": chapter_list, "content": content})

模板:模板遍历一个列表,检查它创建的选项是否是当前章节。如果是这样,它应该“选择”它。

{% for t, o in chapters %}
<option value="/work/{{ info.id }}/{{ o }}" {% if o == info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option>
{% endfor %}

然而,每当我运行代码时,都没有选择任何内容(if 标记中有什么)。通过我所做的调试,我已经确认o是 2 并且info.current_chapter也是 2。

4

2 回答 2

1

在模板中尝试使用单个“=”操作而不是“==”。

<option value="/work/{{ info.id }}/{{ o }}" {% if o = info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option>
于 2012-11-24T05:52:36.453 回答
1

尝试ifequal

 {% for t, o in chapters %}
    <option value="/work/{{ info.id }}/{{ o }}" {% ifequal o info.current_chapter %} selected="selected" {% endifequal %}>Chapter {{ o }}: {{ t }}</option>
    {% endfor %}
于 2012-11-24T07:42:34.183 回答