Search code examples
djangotemplatesmodelmany-to-many

How to render a many to manyfield?


I'm making a todo with a friend and we are trying to render it in our template.

This is my models.py

class Todo(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name="Nom de l'utilisateur")
    text = models.CharField(max_length=150, verbose_name="Nom de la Todo")

class Routine(models.Model):
todo= models.ManyToManyField(Todo)
text = models.CharField(max_length=150,)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.text

My views.py

class DashboardListView(LoginRequiredMixin,ListView):
model = Links
template_name = 'dashboard/home.html'
context_object_name ='links_list'

def get_queryset(self):
    return self.model.objects.filter(author=self.request.user)

def get_context_data(self, **kwargs):

    context = super().get_context_data(**kwargs)

context['todo_list']= Todo.objects.filter(author=self.request.user).order_by('-pk')[:15]        
context['routine_list']= Routine.objects.filter(author=self.request.user).order_by('-pk')[:15]
        return context

And in my template I am trying to render it like that :

  {% for routine in routine_list %} 

{{routine.text|capfirst}}
<br/>{% for todo in routine.todo.all %}{{ text }}<br/>{% endfor %}
{{routine.todo.text|capfirst}}

{% endfor %}

But only the "routine" is being render, any help ?


Solution

  • Try this instead

    {% for routine in routine_list %} 
    
        {{routine.text|capfirst}}
            <br/>{% for todo in routine.todo.all %}{{ todo.text }}<br/>{% endfor %}
        {{routine.todo.text|capfirst}}
    
    {% endfor %}
    

    Specifically, inside the loop, you want to access {{todo.text}} instead of {{text}}