Django for Tag

Django for Tag

For Loops

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

Example

Loop through the items of a list:

Run Example »

Example

Loop through a list of dictionaries:

Run Example »


Data From a Model

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

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

 id  firstname  lastname
 1  Emil  Refsnes
 2  Tobias  Refsnes
 3  Linus  Refsnes
 4  Lene  Refsnes
 5  Stalikken  Refsnes

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:

Example

Loop through items fetched from a database:

Run Example »


Reversed

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

Example

Run Example »


Empty

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

Example

Run Example »

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

Example

Run Example »


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.

Example

Run Example »

forloop.counter0

The current iteration, starting at 0.

Example

Run Example »

forloop.first

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

Example

Draw a blue background for the first iteration of the loop:

Run Example »

forloop.last

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

Example

Draw a blue background for the last iteration of the loop:

Run Example »

forloop.revcounter

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

Example

Run Example »

forloop.revcounter0

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

Example

Run Example »

ArmenianEnglish