Django:模板语言比较总是返回false
问题描述:
在我正在开发的一个项目中,我需要select
标签默认位于特定的option
上。我试图做到这一点,如果我设置一个变量为特定的数字,相应的选项将在页面加载时被选中。出于某种原因,我用来判断选项是否与变量相同的代码始终返回false。Django:模板语言比较总是返回false
View.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。
答
在模板中,尝试使用单个'='操作而不是'=='。
<option value="/work/{{ info.id }}/{{ o }}" {% if o = info.current_chapter %} selected="selected" {% endif %}>Chapter {{ o }}: {{ t }}</option>
答
尝试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 %}
你确定这两个'O'和'info.current_chapter'是同一类型?两者都应该是'int()',但也许其中之一是一个字符串(通常是因为它来自请求变量)。 –
@MartijnPieters我想到了,但我认为它们都是同一类型。 'info.curent_chapter'不是一个请求变量(Wait,do URL parameters count?),'o'来自模型的整数字段。 –
是的,网址参数会计数。再次检查你的类型(使用'repr()'来验证,'print 1'和'print'1''在控制台上看起来是一样的)。 –