【发布时间】:2019-09-09 12:24:41
【问题描述】:
我正在尝试使用 Django 创建一个模板,该模板循环遍历 Posts,并且每个 Post 循环遍历所有图片。 我已经查看了其他问题的一些答案,但找不到我的错误。
型号:
class Post(models.Model):
Post_Title = models.CharField(max_length=200)
Post_pub_date = models.DateField('date published')
Post_Author = models.CharField(max_length=100)
Post_Text = models.TextField()
def __str__(self):
return self.Post_Title
class Picture(models.Model):
Post = models.ForeignKey(Post, on_delete=models.CASCADE)
Picture = models.ImageField()
Picture_Name = models.CharField(max_length=100, null=True, blank=True)
def __str__(self):
return self.Picture_Name
观看次数:
class PostView(generic.ListView):
template_name = 'myblog/index.html'
context_object_name = 'Post_List'
def get_queryset(self):
"""
Returns Posts
"""
return Post.objects.order_by('-Post_pub_date')
模板:
{% for Post in Post_List %}
<h1 class="mb-4">{{Post.Post_Title}}</h1>
<span class="category">{{Post.Post_Author}}</span>
<span class="mr-2">{{Post.Post_pub_date}}</span>
<div class="post-content-body"><p>{{Post.Post_Text}}</p>
{% for Picture in Post.Picture_set.all %}
<div class="col-md-12 mb-4 element-animate">
<h2>{{Picture.Picture_Name}}</h2>
<img class="col-md-12 mb-4 element-animate" src="{{ MEDIA_URL }}{Picture.Picture}}">
</div>
{% endfor %}
</div>
{% endfor %}
Post_Title、Post_Author、Post_pub_date 和 Post_Text 显示正常。只是嵌套的 For 循环不会产生任何 Picture_Name 或 Picture,就好像 Picture_set.all 为空一样。
如上所述,我试图在 this 等不同的帖子中找到我的错误,但找不到。
感谢您的帮助。
【问题讨论】: