Python 如何在Django中创建定时发布?
我想根据指定的日期和时间发布发货 例如,当我今天发送文章时,我希望它在明天的时间到来时自动发布。(或在任何日期和时间) 我怎么做 模型的相关部分: 使用此模型,可以确定post的日期和时间 型号.pyPython 如何在Django中创建定时发布?,python,django,post,time,Python,Django,Post,Time,我想根据指定的日期和时间发布发货 例如,当我今天发送文章时,我希望它在明天的时间到来时自动发布。(或在任何日期和时间) 我怎么做 模型的相关部分: 使用此模型,可以确定post的日期和时间 型号.py published = models.DateTimeField(default=timezone.now, verbose_name="Yayımlanma Tarihi",) created = models.DateTimeField(auto_now_add=True) updated =
published = models.DateTimeField(default=timezone.now, verbose_name="Yayımlanma Tarihi",)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
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})
视图.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)
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})
假设你想在2019年12月1日发表一篇文章。因此,您将保存该帖子,并将发布日期设置为2019年12月1日 但既然那篇文章还没有“发表”,你就不希望它出现在你的网站上。所以,你所要做的就是过滤掉它,只选择那些
发布日期早于当前时间的帖子
例如:
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()
你可能想好好读一读。芹菜其实不是必需的。你所要做的就是过滤掉那些发布日期在将来的帖子。@xyres那么我该怎么做呢?你能给我举个例子吗?这意味着,我不应该在models.py中设置auto\u now\u add
?在published\u lte
中什么是lte
?@Progam是的,auto\u now\u add
不应该设置发布日期,以便用户可以手动选择发布文章的日期。而且,lte
表示小于或等于
。因此,在这个答案中,我们选择的是那些发表日期小于或等于now
的文章,即在now
之前的文章。有没有一种方法(比如\u lte
)来过滤所有未来的文章?@Progam有gt
和gte
。请通读以熟悉api。