On Wed, Jan 20, 2016 at 8:00 PM, sonu kumar <sonunit...@gmail.com> wrote:
> SO link: > http://stackoverflow.com/questions/34894964/why-counter-tag-is-not-working-as-expected-in-django > > I am using two for loop one is for main question and another one is for > sub questions. > Why? We have some comprehension type question, in comprehension type > question there could be more than one questions so one outer for loop is > running for main question and another one is sub questions. > Right. You would have two {% for %} loops. If you look at the table of variables made available for those loops, you can see that you can access the counters for both the inner and outer loops separately. No need for an external template tag to keep track. If all you are doing is automatically numbering questions (and sub-questions with an inner {% for %} loop), then the {% for %} loop already provides everything you need. {% for question in questions %} {{ forloop.counter }}: {{ question}} {% for sub_question in question.sub_questions %} {{ forloop.counter }}: {{ sub_question }} {% endfor %} {% endfor %} Would produce something like: 1: What is your name? 1: Is it Frodo? 2: Is it Harry Potter? 2: What is your quest? 1: To be The Doctor? 2: To seek out new life and new civilizations? 3: To join the dark side? 3: What is your favorite color? 1: Is it blue? 2: Is it yellow? The only instance where I can see the tag being of use is if you are keeping track of a particular type of question that may not match all elements in the loop. Then again, you can also work around that with a proper data structure being fed to your template, and then use filters like |length to figure out how many of each type of question you have. -James -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at https://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CA%2Be%2BciWvxZS4sTeLbbOqYRuFP3kSzgPiT84%3DatQpq6HH0JCfTw%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.