Django模板if语句总是计算为true [英] Django template if statement always evaluates to true
问题描述
这看起来应该很简单,但由于某种原因我无法解决这个问题。我正在使用Django 1.4。我试图在模板渲染过程中进行基本检查以查看列表 QuerySet是否为空,但我正在使用的if语句似乎总是评估为true。
This seems like it should be pretty straightforward, but for some reason I am unable to solve this problem. I'm using Django 1.4. I am trying to do a basic check to see if a list QuerySet is empty or not during template rendering, but the if statement I'm using seems always to evaluate to true.
我有一个Django模板,内容如下:
I have a Django template that reads:
{% extends 'includes/base.html' %}
{% if object_list %}
...
{% block data %}
{% for object in object_list %}
...
{{ object.create_date }}
...
{% endfor %}
{% endblock data %}
...
{% endif %}
'base.html'有块:
'base.html' has the block:
<body>
{% block content %}
...
<div class="row-fluid">
<div class="span12">
{% block data %}
<div align="center"><i>No data.</i></div>
{% endblock data %}
</div><!-- span12 -->
</div><!-- row -->
{% endblock content %}
...
</body>
生成QuerySet的视图函数在这里:
The view function generating the QuerySet is here:
def barcode_track(request, model):
query = request.GET.get('barcode_search', '')
object_list = model.objects.all()
if query:
object_list = model.objects.filter(barcode__icontains=query)
return render_to_response('barcode_track/barcode_list.html',
{'object_list': object_list, 'query': query},
context_instance=RequestContext(request))
这是通过此表单调用:
<form id="barcode_search_form" method="get" action="" class="form">
<input type="text" name="barcode_search" value="{{ query }}" />
<button type="submit" class="btn">Search</button>
</form>
和urls.py行:
urlpatterns = patterns('barcode_track.views',
url(r'^$', 'barcode_track', {'model': Barcode},
name="barcode_track"),)
这个想法是只有在<$存在于<$时才会显示结果c $ c> object_list ,否则父块将保持不变。我尝试更改 object_list
的名称,并在页面上打印 {{dicts}}
以确保 object_list
实际上是空的(它是)。我没有使用通用视图,虽然我意识到这个名字的含义也是如此。实际上我在使用类似逻辑编写的其他应用程序中遇到了这个问题,所以我必须系统地做错误的事情。
The idea is that results will only be presented if they exist in object_list
, and otherwise the parent block will remain unaltered. I have tried changing the name of object_list
, and I have printed {{ dicts }}
to the page to ensure that object_list
is, in fact, empty (which it is). I am not using a generic view, although I realize that the name suggests as much. I have actually had this trouble in a different app I wrote using similar logic, so I must be doing something systematically incorrectly.
我在这里缺少什么?
推荐答案
你不能将之类的控制流标签包装在
附近
块
。您的问题是,子模板的块数据
的定义正在被使用,因为它就在那里。
You can't wrap control flow tags like if
around a block
. Your problem is that the child template's definition for block data
is being used simply because it's there.
你可以修复它通过在块数据
中放置 if
标记。如果要在列表为空时继承父级内容,请添加 else
大小写扩展为 {{block.super}}
。
You can fix it by placing the if
tag inside block data
. If you want to inherit the parent's contents when the list is empty, add an else
case that expands to {{ block.super }}
.
这篇关于Django模板if语句总是计算为true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!