TanyaG TanyaG - 21 days ago 8
HTML Question

Iterating Through Many to Many Model

I have a model like so:

`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')


`
I'm having trouble writing out the view for it, essentially

<li>task #1</li>
<li>subtask#1.1</li>
<li>subtask#1.2</li>
<li>task #2</li>
<li>subtask#2.1</li>
<li>subtask#2.2</li>
.
.
.
.


I tried creating a for loop to iterate through them using but it doesn't show up nested like how I would want it

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

Answer

This is an HTML issue rather than with your django code

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

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