在我正在处理的项目中,我需要默认情况下将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。