SSun SSun - 1 year ago 69
HTML Question

checking django empty table object not working

I've an html page, I'd like to display the search bar only when the passed in table object is NOT empty. But my check is not working properly. Here's the code:

<!-- We'll display the search bar only when the user has access to at least one item, otherwise, hide it. -->
{% if item_info %}
Number of entries: {{ item_info|length }}, nothing? {{item_info}}
<form method="post" action=".">
{% csrf_token %}
<input type="text" class="search-query span80" id="search" name="search" placeholder="Enter ItemNo to search">
<button type="submit" class="btn">Search</button>
{% else %}
No item_info.
{% endif%}

Here's what I see on the browser:
still enters if branch

item_info is blank, I think it should go to else branch, however, it entered if branch, any help is greatly appreciated!

Answer Source

If item_info is a RawQuerySet, try {% if item_info.all %} instead of {% if item_info %}. RawQuerySet does not define a __bool__() method, so the instances are always considered True. See the warnings in this section of the docs, repeated below, just in case this link dies in the future:

While a RawQuerySet instance can be iterated over like a normal QuerySet, RawQuerySet doesn’t implement all methods you can use with QuerySet. For example, bool() and len() are not defined in RawQuerySet, and thus all RawQuerySet instances are considered True. The reason these methods are not implemented in RawQuerySet is that implementing them without internal caching would be a performance drawback and adding such caching would be backward incompatible.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download