我无法仅在模板中将布尔字段设置为true的情况下显示帖子

时间:2019-02-14 18:44:22

标签: python html django wagtail

简而言之-我有一个自举轮播,效果很好,但是我无法让它仅显示“功能”设置为“真”的字段

我尝试过进行for post in posts.objects.featured(轮播实际上根本不显示)和类似posts.objects.filter(featured=True)的变体(它说无法解析其余部分)。

这是模板中的代码,我试图在其中显示轮播图片,仅显示具有Featured = True的项目


{% for post in posts.objects.featured %}
  <div class="carousel-item {% if forloop.first %}active{% endif %} ">
  {% image post.image fill-1920x500 %}
   <div class="carousel-caption d-none d-md-block">
      <h2 id="inner-carousel-title">{{post.title}}</h2>
      <h4><a href="{% pageurl post %}" style="color:white;text-shadow:2px 2px 4px #000000" >something</a></h4>
   </div>
  </div>
{% endfor %}

再说一次,我只希望轮播只在精选帖子中显示 附带说明-如果只显示3个帖子,那就太好了。

编辑-这是页面的我的model.py

    class BlogPage(RoutablePageMixin, Page):
        description = models.CharField(max_length=240, blank=True)

        content_panels = Page.content_panels + \
            [FieldPanel("description", classname="full")]

        def get_context(self, request, *args, **kwargs):
            context = super(BlogPage, self).get_context(request, *args, **kwargs)
            context['posts'] = self.posts
            context['blog_page'] = self
            return context

2 个答案:

答案 0 :(得分:1)

如果您确实要在模板中执行此操作,请执行以下操作:

{% for post in posts %}
    {% if post.featured %}
        <div> ... <div/>
    {% endif %}
{% endfor %}

但是您也可以仅将精选文章传递到视图中的模板。只需添加:

...
featured_posts = Post.objects.filter(featured=True)[:4]
return render('post_list.html', {'featured_posts': featured_posts, ...})

如果您使用的是Django的通用ListView,而只显示精选的帖子,则可以设置queryset属性以仅过滤精选的帖子。如果您还要在ListView中显示其他帖子,请通过覆盖get_context_data()来将Featured_posts添加到您的上下文中。

答案 1 :(得分:0)

如果我在评论中建议的方式不起作用,您可以尝试一下

{% for post in posts %}
    {% if post.featured %}
        // write down your stuff
    {% endif %}
{% endfor %}