如何呈现多对多字段?

时间:2019-05-09 17:23:58

标签: django templates model many-to-many

我正在和一个朋友一起做待办事项,我们正在尝试在模板中渲染它。

这是我的 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

我的 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

在我的模板中,我试图像这样渲染它:

  {% for routine in routine_list %} 

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

{% endfor %}

但是只有“例程”正在渲染,有帮助吗?

1 个答案:

答案 0 :(得分:1)

试试看

{% for routine in routine_list %} 

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

{% endfor %}

具体地说,在循环内部,您要访问{{todo.text}}而不是{{text}}