Thanks for the answer Daniel Roseman
Note that it only has access to the previous item if there is no other condition
Maybe I could not explain well, let me give an example
View.py:
...
context = {
'cars': [
{
'brand': 'Ford',
'model': 'Mustang',
'year': '1964',
},
{
'brand': 'Ford',
'model': 'Bronco',
'year': '1970',
},
{
'brand': 'Ford',
'model': 'Sierra',
'year': '1981',
},
{
'brand': 'Volvo',
'model': 'XC90',
'year': '2016',
},
{
'brand': 'Volvo',
'model': 'P1800',
'year': '1964',
}]
}
...
Templates:
{% for x in cars %}
{% if forloop.counter == 1 %}
if first condition true
<span>{{x.brand}}</span>
{% else %}
if first condition false
{% ifchanged x.brand %}
<span>{{x.brand}}</span>
{% else %}
<span>{{x.name}}</span>
{% endifchanged %}
{% endif %}
{% endfor %}
In this case, according to the first condition(The condition can be anything), the first item is never compared with {% ifchanged %}
, so as a result, you see two "Ford", even though they are both from the same brand.
So {% ifchanged %}
check if a value has changed from the last iteration of a loop, if there is no other conditions.