Search code examples
djangotemplatesif-statementblockconditional-statements

Django template if statement always evaluates to 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.

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' 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>

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))

Which is called via this form:

<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>

And the urls.py line:

urlpatterns = patterns('barcode_track.views',
                       url(r'^$', 'barcode_track', {'model': Barcode},
                           name="barcode_track"),)

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.

What am I missing here?


Solution

  • 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.

    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 }}.