How to check if django-tables2 table is empty or not in templates code?

In Django-Tables2, you can check if a table is empty or not by checking the length of the table’s queryset. If the length is zero, then the table is empty. You can do this in your template code using the if statement and the table.queryset attribute.

Here’s an example of how to do this in your template code:

{% if table.queryset|length == 0 %}
    <p>The table is empty.</p>
{% else %}
        <!-- table code here -->
{% endif %}

In this example, we first check the length of the table.queryset attribute using the length filter. If the length is zero, we display a message saying that the table is empty. Otherwise, we display the table code.

As an alternative, you can try to check if .rows of your table exists:

{% if not transactions_success_all_table.rows %}
                                        <h4 class="header-title mb-4 float-sm-start">{% translate 'No successful transactions yet' %}</h4>
                                    {% else %}
                                        <h4 class="header-title mb-4 float-sm-start">{{ transactions_made }} {% translate "successful transactions" %}:</h4>
                                        <div class="clearfix"></div>
                                        <div class="table-responsive custom1">
                                            {% render_table transactions_success_all_table 'partials/vanilla_table.html' %}
                                    {% endif %}


You can customize the message or HTML as per your requirements.


This is part of the Django tips and tricks series. If you’re interested in developing Django apps – don’t miss my Django questions and answers category.

Leave a Comment