python - 如何在 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})
解决方案
假设您想在 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()
推荐阅读
- sql - 将查询结果转换为 postgresql 中的一个数组 json 对象
- reactjs - ColorPicker material-ui-color,鼠标上移设置颜色
- c - 带动态数组的 Fscanf
- java - 在 Java Netbeans (UCanAccess) 中插入来自不同数据库的值
- css - 用渐变填充 SVG
- python - 光标移动时如何保持相同的帧速率?
- python - 通过 Python smtplib 发送电子邮件在远程 linux 服务器上不起作用
- google-apps-script - Google App Script - TypeError:无法读取未定义的属性“getResponse”
- signalr - SignalR 客户端断开连接
- reactjs - 选择上的 forwardRef 不会使用 react-hook-form 保存选择的值