Django Tutorial · Django Syntax

Django For Loop

Learn all about Django For Loop in this comprehensive tutorial.

5 min read intermediate
  • A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.
  • Data in a model is like a table with rows and columns.
  • The reversed keyword is used when you want to do the loop in reversed order.
  • The empty keyword can be used if you want to do something special if the object is empty.
  • Django has some variables that are available for you inside a loop:
  • The current iteration, starting at 1.
  • The current iteration, starting at 0.
  • Allows you to test if the loop is on its first iteration.
  • Allows you to test if the loop is on its last iteration.
  • The current iteration if you start at the end and count backwards, ending up at 1.
  • The current iteration if you start at the end and count backwards, ending up at 0.

For Loops

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.

Data From a Model

Data in a model is like a table with rows and columns.

The Member model we created earlier has five rows, and each row has three columns:

When we fetch data from the model, it comes as a QuerySet object, with a similar format as the cars example above: a list with dictionaries:

Reversed

The reversed keyword is used when you want to do the loop in reversed order.

Empty

The empty keyword can be used if you want to do something special if the object is empty.

The empty keyword can also be used if the object does not exist:

Loop Variables

Django has some variables that are available for you inside a loop:

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

forloop.counter

The current iteration, starting at 1.

forloop.counter0

The current iteration, starting at 0.

forloop.first

Allows you to test if the loop is on its first iteration.

forloop.last

Allows you to test if the loop is on its last iteration.

forloop.revcounter

The current iteration if you start at the end and count backwards, ending up at 1.

forloop.revcounter0

The current iteration if you start at the end and count backwards, ending up at 0.

Module quiz

2 questions
1

Which of the following is true about Django For Loop?

2

What is the most common pitfall when working with Django For Loop?

Answer all questions to submit.