You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中仅为两天内新建的内容显示SVG图标

解决仅显示两天内新内容SVG图标的问题

要实现只给过去两天内创建的内容显示SVG图标,我们需要先计算出两天前的时间节点,再在模板里对比内容的创建时间是否在这个节点之后。具体步骤如下:

1. 修改视图文件(views.py)

首先引入日期时间相关模块,计算出两天前的时间点,然后把这个变量传递给模板:

from datetime import timedelta
from django.shortcuts import render
from django.utils import timezone  # 项目启用时区时必须用这个,保证时间对比准确
from . import models  # 确保正确导入你的模型

def short_story_list(request):
    # 计算两天前的时间节点
    two_days_ago = timezone.now() - timedelta(days=2)
    # 保留原有的内容查询逻辑
    shorts = models.Short.objects.filter(is_live=True).order_by('-created_at')
    # 将时间变量传入模板
    return render(request, 'stories/short_story_list.html', {'shorts': shorts, 'two_days_ago': two_days_ago})

小贴士:如果你的项目未启用时区(不推荐生产环境这么做),可以把timezone.now()换成datetime.datetime.now(),记得提前导入datetime模块。

2. 修改模板文件(short_story_list.html)

把原来的判断条件替换成「内容创建时间晚于两天前」的逻辑:

{% for short in shorts %}
 <div class="block">
 <h3><a href="{% url 'short-detail' short.slug %}">{{ short.title }}</a></h3>
 {% if short.created_at >= two_days_ago %}
 <img src="{% static 'svg/outline-fiber_new-24px.svg' %}">
 {% endif %}
 <br>
 </div>
{% endfor %}

这样修改后,只有过去两天内新建的内容才会显示指定的SVG图标,完全符合你的需求~

内容的提问来源于stack exchange,提问作者thelastchosen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:27