How to use “for-loop with else” in Django Template?

How to use “for-loop with else” in Django Template?

Are you trying to use “for loop with else” in the Django template? I know we do that in Python programming. Unfortunatily that does not work with the Django template.

for loop with else in Python

If the iterable object is empty and if you want to print that (or execute a different block of code), you can use the else block.

Here we are iterating over an empty Python list and it will execute else block.

sample_list = []

for item in sample_list:
    print(item)
else:
    print("List is empty.")

Output:

List is empty.

You can read more detail about the conditional loop in Python.

Unlike Python, the Django template does not support for-else block. There is another method called for-empty.

for loop with empty in Django template

Suppose now you are sending a query object (list of records) to the Django template to show that on the HTML page.

For example, I was working on one of the eCommerce Django projects where we are listing all the products from specific sellers.

There can be a case where sellers don’t have any product listed. In that case, we had to show messages like “Seller has not listed any product to sell.”

This is how you can achieve in Python Django template using for loop with the empty keyword.

{% for product in products %}
   <div>product.name</div>
 {% empty %}
   <div>Seller has not listed any product to sell.</div>
 {% endfor %}

This is how you can implement for-loop with else in the Django template. This is a very simple and useful trick. Stay tuned for more of such tricks.

Leave a Reply

Your email address will not be published. Required fields are marked *