Fisher Coder
Fisher Coder

Reputation: 3576

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}}
<section>
    <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> 
    </form>
</section>
{% 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!

Edit after elethan's answer: I've printed it out to debug, here's the screenshot: 2nd_img So, looks like this item_info is really empty, I didn't see any item_info object gets printed out.

Also, to help debug, here's my view code:

def item_info(request):    
    iteminfo= ItemInfo.objects.all().filter(Q(some_query)
    table = ItemInfoTable(iteminfo)
    RequestConfig(request).configure(table)
    return render(request, 'item_info.html', {'item_info':table,})

And here's my table definition:

import django_tables2 as tables  
class ItemInfoTable(tables.Table):
    itmno = tables.Column(verbose_name="Item #")
    class Meta:
        model = ItemInfo
        empty_text = "There is no item record." 

And here's the ItemInfo table it refers to:

class ItemInfo(models.Model):
    itmno = models.CharField(primary_key=True, max_length=11L, db_column='ItmNo', blank=True)
    class Meta:
        db_table = 'item_info'

Upvotes: 2

Views: 882

Answers (1)

elethan
elethan

Reputation: 17003

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.

Upvotes: 2

Related Questions