django模板中嵌套的for Loop有什么问题?

时间:2019-04-19 07:42:50

标签: python django

我正在尝试使用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之类的不同帖子中找到我的错误,但找不到它。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

按照向后关系,即使模型名称以大写字母开头,也需要用小写字母写出相关模型名称:

{% for Picture in Post.picture_set.all %}

这是它在Django Shell中的工作方式,我想在模板中是相同的。

答案 1 :(得分:0)

问题不是嵌套的for循环,而是视图。它仅返回对Post的查询,您不会将任何照片传递给模板。