Django template: get the total number of iterations for nested loops

I have two nested loops inside a template. I need to get the final iterations made since the start of the parent loop. The counter should only increase when the child iterates through.

For instance:

Each cycle goes from 1 to 3 (included)

Parent cycle - 1st iteration

Children's cycle - 3rd iteration

Required Result: 3

Parent cycle - second iteration

Children's cycle - 1st iteration

Required Result: 4

Can this be done using standard Django template tags? If not, what are my options?

+4
source share
4 answers

count, .

{% for ... %}
  {% for ... %}
    {% count totalloops %}
  {% endfor %}
{% endfor %}
{{ totalloops }}
+2

, , ?

, :

{{forloop.counter | : forloop.parentcounter.counter}} ..

( @Ignacio), , .

+1

{{forloop.counter | add: forloop.parentcounter.counter}}, , , python, django.,

add-

class make_incrementor(object):
    count = 0

    def __init__(self, start):
        self.count = start

    def inc(self, jump=1):
        self.count += jump
        return self.count

    def res(self):
        self.count = 0
        return self.count

def EditSchemeDefinition(request, scheme_id):

    iterator_subtopic = make_incrementor(0)
    scheme_recs = scheme.objects.get(id=scheme_id)
    view_val = {
        'iterator_subtopic': iterator_subtopic,
        "scheme_recs": scheme_recs,
    }
    return render(request, "edit.html", view_val)

django "iterator_subtopic" , :

<td id="subTopic" class="subTopic">
<p hidden value="{{ iterator_subtopic.res }}"></p>
{% for strand in  scheme_recs.stand_ids.all %}
    {{ iterator_subtopic.res }}
    {% for sub_strand in  strand.sub_strand_ids.all %}
        {% for topic in  sub_strand.topic_ids.all %}
            {% for subtopic in  topic.sub_topic_ids.all %}
                <input id="subTopic{{ iterator_subtopic.inc  }}" class="len"
                       value="{{ subtopic.name }}">
                <br>
            {% endfor %}
        {% endfor %}
    {% endfor %}
{% endfor %}

, , , .

+1
source

With class-based views (specifically, using Python 3 and Django 2.1) and using @Javed's answer as a starting point, in the view, you can do:

class Accumulator:

    def __init__(self, start=0):
        self.reset(start)

    def increment(self, step=1):
        step = 1 if not isinstance(step, int) else step
        self.count += step
        return self.count

    def reset(self, start=0):
        start = 0 if not isinstance(start, int) else start
        self.count = start
        return self.count

class MyView(ParentView):

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['counter'] = Accumulator()  # use start=-1 for a zero-based index.
        return context

Then in the template you can do:

{% with counter.increment as count %}
  <input id="form-input-{{ count }}">
{% endwith %}
0
source

Source: https://habr.com/ru/post/1778429/


All Articles