首页 > 解决方案 > 如何在 Django 中创建预定的帖子?

问题描述

我想根据指定的日期和时间发布货物。

比如我今天发文章,希望明天到时候自动发表。(或在任何日期和时间)

我该怎么做?

模型的相关部分:

使用此模型,可以确定发布的日期和时间。

模型.py

published = models.DateTimeField(default=timezone.now, verbose_name="Yayımlanma Tarihi",)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)

视图.py

def post_index(request):
    post_list = Post.objects.all()
    query = request.GET.get('q')
    if query:
        post_list = post_list.filter(
            Q(title__icontains=query) |
            Q(content__icontains=query) |
            Q(author__first_name__icontains=query) |
            Q(author__last_name__icontains=query)
        ).distinct()

    paginator = Paginator(post_list, 5) # Show 25 contacts per page

    page = request.GET.get('sayfa')
    posts = paginator.get_page(page)

    return render(request, 'post/index.html', {'posts': posts})

标签: pythondjangoposttime

解决方案


假设您想在 2019 年 12 月 1 日发布帖子。因此,您将保存该帖子,并将published日期设置为 2019 年 12 月 1 日。

但由于该帖子尚未“发布”,您不希望它出现在您的网站上。因此,您所要做的就是将其过滤掉,只选择published日期早于当前时间的那些帖子。

例子:

from django.utils import timezone

now = timezone.now() # get the current time

# only select the posts which are `published` before `now`
post_list = post_list.filter(
    published__lte=now
).filter(
    Q(title__icontains=query) |
    Q(content__icontains=query) |
    # ... etc ... 
).distinct()

推荐阅读