When looping over a sequence, such as through entries in an array, list, or dictionary, a for loop is utilized.

For Tag Django
For Tag Django

Example

Loop through a list’s items:

{% for x in fruits %}
  <h1>{{ x }}</h1>
{% endfor %}

Example

Loop through a dictionary list:

{% for x in cars %}
  <h1>{{ x.brand }}</h1>
  <p>{{ x.model }}</p>
  <p>{{ x.year }}</p>
{% endfor %} 

Information From a Model

A model’s data is comparable to a table with rows and columns.

Each of the five rows in the Member model we previously generated has three columns:

 id  firstname  lastname  phone  joined_date 
 1  Emil  Refsnes  5551234  2022-01-05 
 2  Tobias  Refsnes  5557777  2022-04-01 
 3  Linus  Refsnes  5554321  2021-12-24 
 4  Lene  Refsnes  5551234  2021-05-01 
 5  Stalikken  Refsnes  5559876  2022-09-29 

A QuerySet object, which resembles the vehicles example above in format, is what we get when we retrieve data from the model: a list with dictionaries

<QuerySet [
  {
    'id': 1,
    'firstname': 'Emil',
    'lastname': 'Refsnes',
    'phone': 5551234,
    'joined_date': datetime.date(2022, 1, 5)
  },
  {
    'id': 2,
    'firstname': 'Tobias',
    'lastname': 'Refsnes'
    'phone': 5557777,
    'joined_date': datetime.date(2021, 4, 1)
  },
  {
    'id': 3,
    'firstname': 'Linus',
    'lastname': 'Refsnes'
    'phone': 5554321,
    'joined_date': datetime.date(2021, 12, 24)
  },
  {
    'id': 4,
    'firstname': 'Lene',
    'lastname': 'Refsnes'
    'phone': 5551234,
    'joined_date': datetime.date(2021, 5, 1)
  },
  {
    'id': 5,
    'firstname': 'Stalikken',
    'lastname': 'Refsnes'
    'phone': 5559876,
    'joined_date': datetime.date(2022, 9, 29)
  }
]> 

Example

Loop through the entries that were retrieved from a database:

{% for x in members %}
  <h1>{{ x.id }}</h1>
  <p>
    {{ x.firstname }}
    {{ x.lastname }}
  </p>
{% endfor %} 

Inverse

To perform the loop in reverse order, use the reversed keyword.

Example

{% for x in members reversed %}
  <h1>{{ x.id }}</h1>
  <p>
    {{ x.firstname }}
    {{ x.lastname }}
  </p>
{% endfor %}  

Empty

If the object is empty, you can use the empty keyword to perform anything unique.

Example

<ul>
  {% for x in emptytestobject %}
    <li>{{ x.firstname }}</li>
  {% empty %}
    <li>No members</li>
  {% endfor %}
</ul> 

If there is no object, the empty keyword can also be used:

Example

<ul>
  {% for x in myobject %}
    <li>{{ x.firstname }}</li>
  {% empty %}
    <li>No members</li>
  {% endfor %}
</ul> 

Variables in Loops

In a loop, you can access the following variables in Django:

• forloop.counter
• forloop.counter
• forloop.counter0
• forloop.counter0
• forloop.first
• forloop.last
• forloop.parentloop
• forloop.revcounter
• forloop.revcounter0

forloop.counter

The current version, which begins at 1.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.counter }}</li>
  {% endfor %}
</ul> 

forloop.counter0

Starts at 0 in the current iteration.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.counter0 }}</li>
  {% endfor %}
</ul> 

forloop.first

Enables you to determine whether the loop is in its initial iteration.

Example

Create a blue backdrop for the loop’s initial iteration:

<ul>
  {% for x in fruits %}
    <li
      {% if forloop.first %}
        style='background-color:lightblue;'
      {% endif %}
    >{{ x }}</li>
  {% endfor %}
</ul> 

forloop.last

Enables you to determine whether the loop is in its final iteration.

Example

Create a blue backdrop for the loop’s last iteration:

<ul>
  {% for x in fruits %}
    <li
      {% if forloop.last %}
        style='background-color:lightblue;'
      {% endif %}
    >{{ x }}</li>
  {% endfor %}
</ul> 

forloop.revcounter

If you begin at the end and count backwards, you will arrive at 1 in the current iteration.

<ul>
  {% for x in fruits %}
    <li>{{ forloop.revcounter }}</li>
  {% endfor %}
</ul> 

forloop.revcounter0

The current iteration would be zero if you started at the end and counted backwards.

Example

<ul>
  {% for x in fruits %}
    <li>{{ forloop.revcounter0 }}</li>
  {% endfor %}
</ul> 

Django Comment Tagging

You can include code that should be disregarded in comments.

<h1>Welcome Everyone</h1>
{% comment %}
  <h1>Welcome ladies and gentlemen</h1>
{% endcomment %}

Understanding the Comment

To assist you recall why you created the comment or to convey a message to other readers of the code, you can include a note in your comment.

Example

Add your remark a description:

<h1>Welcome Everyone</h1>
{% comment "this was the original welcome message" %}
    <h1>Welcome ladies and gentlemen</h1>
{% endcomment %}

Micro-comments

Additionally, you may utilize the {#… #} tags, which can make it simpler for smaller comments, when commenting out code:

Example

Leave a comment with the word “Everyone”:

<h1>Welcome{# Everyone#}</h1>

Comments within View Functions

Python is used to write views, and the # symbol is used to write Python comments:

Example

Leave a comment in the view:

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  #context = {
  # 'var1': 'John',
  #}
  return HttpResponse(template.render())

Using Django’s include Tag

Using the include tag, you can insert a template inside the one that already exists.

Having a block of content that is the same across multiple pages is helpful.

Example

templates/footer.html:

<p>You have reached the bottom of this page, thank you for your time.</p>

templates/template.html:

<h1>Hello</h1>

<p>This page contains a footer in a template.</p>

{% include 'footer.html' %} 

Included Template Variables

The with keyword allows you to send variables into the template.

The {{ variablename }} syntax is used to refer to the variables in the inclusion file:

Example

templates/mymenu.html:

<div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div>

templates/template.html:

<!DOCTYPE html>
<html>
<body>

{% include "mymenu.html" with me="TOBIAS" sponsor="W3SCHOOLS" %}

<h1>Welcome</h1>

<p>This is my webpage</p>

</body>
</html> 

Categorized in: