-1

Can some one please explain me why the below code is not adding the value in current_count variable. Also I am using django version 1.3. The below code gives following output.

0

"image"

10

"image"

10

"image"

. . .

The "image" means actual image is shown.

What I want is "only show 4 images".

{% with current_count=0 %}
    {% for row in people|slice:":4" %}
        {% if row %}
            {% for event in row %}
                {% if current_count < 4 %}
                    {{current_count}}
                    <div class="latest-photos-image-box">
                        <a href="{{ event.get_absolute_url }}"><img src="{{ event.mainthumb.url }}" alt="{{ event.title }}" /></a>
                    </div>
                {% endif %}
                {{ current_count|add:"1" }}
            {% endfor %}
        {% endif %}
    {% endfor %}
{% endwith %}
Muneeb Ahmad
  • 180
  • 1
  • 1
  • 14

2 Answers2

-1
{% for event in row|slice:":4" %}

And get rid of the rest.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • There can be a scenario where there are only 2 events in one row. So I need to look into all the rows too. – Muneeb Ahmad Jul 10 '13 at 10:59
  • Slicing the events of the current row won't prevent you from looking at the other rows. – Ignacio Vazquez-Abrams Jul 10 '13 at 13:21
  • The thing is, There can be an instance where row1 has 1 event row2 has 8 events and row 3 also has 2 events. But I just need to show the first four. In above scenario 1 event from row 1 and first 3 events of row 2 will be shown. That is why I am keeping a "current_count" but it is not getting incremented correctly as I have mentioned in my question. – Muneeb Ahmad Jul 10 '13 at 19:16
  • Erm, no. That's not what that line does. – Ignacio Vazquez-Abrams Jul 10 '13 at 20:21
-1

The problem here is that {{ current_count|add:"1" }} does the addition but doesn't store anything. Please use the loop counters forloop.counter instead.

However, if you need a counter that works regardless of nesting level; here is a recipe (haven't tested but should work):

>>> def monotonic():
...    count = 0
...    while True:
...       yield count
...       count += 1
... 
>>> counter = monotonic()
>>> # pass it to you request context dictionary

and use {{ counter.next }} each time you need it.

Please also check out this question: Flatten list of lists , you may want to flatten your list of rows of people to a more simple list of people that you can then slice.

Community
  • 1
  • 1
dnozay
  • 23,846
  • 6
  • 82
  • 104
  • Thanks for helping out @dnozay. If `{{ current_count|add:"1" }}` does not add, then why in second and third iteration it shows `10` instead of `0`. – Muneeb Ahmad Jul 13 '13 at 14:16
  • 1
    I think it did `"1"` + `"0"` = `"10"`. The fact that you get the same value for both your second **and** third iteration is because there is no assignment being done. – dnozay Jul 13 '13 at 16:44