我想在Django的一个模板html页面中演示两层“ for”循环。第一层是主题,第二层是每个主题下的条目。这是主题和主题的view.py。
def topics(request):
topics = Topic.objects.filter(owner=request.user).order_by("date_added")
context = {"topics": topics}
return render(request, "project/topics.html", context)
def topic(request, topic_id):
topic = Topic.objects.get(id=topic_id)
entries = topic.entries.order_by("-date_added")
context = {"entries": entries}
return render(request, "project/topic.html", context)
在topic.html模板中,我想演示以下主题以及每个主题下的每个条目。但是我怎么能做到呢?
{% for topic in topics %}
<a href="{% url 'project:topic' topic.id %}">{{ topic.text }}</a>
{% for entry in entries %}
<a href="{% url 'project:entry' entry.id %}">{{ entry.text }}</a>
我尝试提供的链接(nested for loops inside templates),但似乎不起作用。这是模板中的脚本。您能帮忙吗?
{% for topic in topics %}
{% for entry in topic.entries_set.all %}
<a href="{% url 'project:entry' entry.id %}">{{ entry.text }}</a>
{% endfor %}
{% endfor %}
这是模型:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
owner = models.ForeignKey(User, on_delete=models.CASCADE)
class Topic(models.Model):
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def _str_(self):
return self.text
class Entry(models.Model):
topic = models.ForeignKey(Topic, on_delete=models.CASCADE, related_name="entries")
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
class Meta:
verbose_name_plural = 'entries'
def _str_(self):
return self.text[:50] + "..."
#on_delete=models.CASCADE,