过滤Mezzanine中发布的BlogPosts

时间:2016-02-14 18:14:06

标签: python django django-models mezzanine

目前在Mezzanine中,我有一些博客文章即将发布,但日期会在几天后发布。

目前,通过按上下文返回这些对象,可以查看这些博客文章对象。如何过滤掉尚未发布的内容?如果我转到博客文章网址,它会给我一个404错误,所以这是正确的。

型号:

class BlogPost(Displayable, Ownable, RichText, AdminThumbMixin):
    """
    A blog post.
    """

    categories = models.ManyToManyField("BlogCategory",
                                        verbose_name=_("Categories"),
                                        blank=True, related_name="blogposts")
    allow_comments = models.BooleanField(verbose_name=_("Allow comments"),
                                         default=True)
    comments = CommentsField(verbose_name=_("Comments"))
    rating = RatingField(verbose_name=_("Rating"))
    featured_image = FileField(verbose_name=_("Featured Image"),
        upload_to=upload_to("blog.BlogPost.featured_image", "blog"),
        format="Image", max_length=255, null=True, blank=True)
    related_posts = models.ManyToManyField("self",
                                 verbose_name=_("Related posts"), blank=True)

    admin_thumb_field = "featured_image"

    class Meta:
        verbose_name = _("Blog post")
        verbose_name_plural = _("Blog posts")
        ordering = ("-publish_date",)

    def get_absolute_url(self):
        """
        URLs for blog posts can either be just their slug, or prefixed
        with a portion of the post's publish date, controlled by the
        setting ``BLOG_URLS_DATE_FORMAT``, which can contain the value
        ``year``, ``month``, or ``day``. Each of these maps to the name
        of the corresponding urlpattern, and if defined, we loop through
        each of these and build up the kwargs for the correct urlpattern.
        The order which we loop through them is important, since the
        order goes from least granular (just year) to most granular
        (year/month/day).
        """
        url_name = "blog_post_detail"
        kwargs = {"slug": self.slug}
        date_parts = ("year", "month", "day")
        if settings.BLOG_URLS_DATE_FORMAT in date_parts:
            url_name = "blog_post_detail_%s" % settings.BLOG_URLS_DATE_FORMAT
            for date_part in date_parts:
                date_value = str(getattr(self.publish_date, date_part))
                if len(date_value) == 1:
                    date_value = "0%s" % date_value
                kwargs[date_part] = date_value
                if date_part == settings.BLOG_URLS_DATE_FORMAT:
                    break
        return reverse(url_name, kwargs=kwargs)

有没有办法只检索真正发布的帖子?

3 个答案:

答案 0 :(得分:1)

  

有没有办法只检索真正发布的帖子?

使用查询publish_date <= today

抓取今天或之前发布的博文
import datetime

BlogPost.objects.filter(publish_date__lte=datetime.date.today())

答案 1 :(得分:0)

您发现未发布的帖子是因为您已经过身份验证,如果您注销,您只会看到已发布的帖子。

答案 2 :(得分:0)

有什么方法可以根据类别过滤帖子并显示帖子列表。