【问题标题】:What is wrong with my nested for Loop in a django Template?我在 django 模板中嵌套的 for 循环有什么问题?
【发布时间】: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 等不同的帖子中找到我的错误,但找不到。

感谢您的帮助。

【问题讨论】:

    标签: python django


    【解决方案1】:

    关系倒退,相关型号名需要小写,即使型号名以大写开头:

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

    这就是它在 Django shell 中的工作方式,我想在模板中它是一样的。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多