2

I'm trying to learn Django but I need help because I'm having trouble understanding.

how can I iterate through all of my models without having to write for loops for each level of tasks that I have?

Example but like infinite sub tasks:

  1. Task #1

    1.1 Subtask #1

    1.2 Subtask #2

    1.2.1 Subsubtask #3

  2. Task #2

    2.1 Subtask #4

    .

    .

    .

    .

My model many to many field on itself

  class task(models.Model):

  name = models.CharField(max_length=100)

  notes = models.TextField()

  created = models.DateTimeField()

  created_by = models.ForeignKey(User)

  subtask = models.ManyToManyField('self')

My template

{% for task in items %}
 <li>{{ task.name }}
   <ul>

    {% for subtask in task.subtask.all %}
      <li>{{ subtask.name }}</li>
    {% endfor %}
  </ul>
 </li>
{% endfor %}

How can I use a template tag to infinite for loop down tasks

TanyaG
  • 79
  • 1
  • 6
  • I really need to iterate over a manytomany field. Recursion won't cut it for me. Did you find a solution to that? – Windfish Sep 20 '22 at 07:14

1 Answers1

2

You should use some form of recursion. Django does allow the recursive use of the include template tag (as described in this answer):

# tasks.html

{% if items %}
  <ul>
    {% for task in items %}
      <li>
        {{ task.name }}
        {# recursively include template itself #}
        {% with items=task.subtask.all template_name="tasks.html" %}  
          {% include template_name %}
      </li>
    {% endfor %}
  </ul>
{% endif %}

Now you can include "tasks.html" in any other template:

{% include "tasks.html" with items=items %}

It is probably better practice to implement a custom tag, and move the recursive code out of the template, but the principle remains the same. On a different note, your current model structure does not prevent your task graph from being circular: if e.g. two tasks are each other's subtasks, you end up with infinite recursion.

Community
  • 1
  • 1
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • Good point on the circular subtasks. Why is it better to implement a custom tag rather than using the with? – TanyaG Nov 13 '16 at 00:22
  • The use of "`with`" is already some kind of kung-fu preventing the template compiler from recursing infinitely... In addition, Python is a more more powerful language than the django templating language, thus, makes it easier (or possible at all) to implement serious logic, s.a. preventing infinite recursion by e.g. collecting visited tasks or sth similar. – user2390182 Nov 13 '16 at 00:27