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

Django IndexView无法刷新实时当前日期问题咨询

解决Django IndexView中查询时间不实时更新的问题

这个现象不是IndexView导致的,完全不需要更换其他视图。问题根源在于你把now = datetime.now()定义成了类属性——类属性是在Django应用启动、类加载的瞬间初始化的,只会执行一次,所以后续所有请求里,now的值都会停留在应用启动时的时间点。

你只需要修改代码,让当前时间在每次请求时重新计算即可,最标准的做法是重写ListView的get_queryset方法:

from django.utils import timezone
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic
from .models import Match

class IndexView(LoginRequiredMixin, generic.ListView):
    """View class for home page"""
    template_name = 'core/index.html'
    model = Match
    context_object_name = 'match_list'

    def get_queryset(self):
        # 每次请求都会执行这里,获取实时的当前时间
        now = timezone.now()
        return Match.objects.filter(season__is_active=True, date_time__range=(now, "2050-12-31"))

补充说明:

  • 推荐使用django.utils.timezone.now()而非原生的datetime.now(),它会自动适配你在Django配置中设置的TIME_ZONE,避免时区不一致引发的时间错误。
  • ListView的queryset类属性属于静态查询集,只会在类加载时构造一次;而get_queryset方法会在每次HTTP请求触发时调用,正好满足你需要实时时间的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 13:30:50