You need to enable JavaScript to run this app. Django日历项目:实现跨起止日期多日同步显示事件的问题
优惠活动
大模型
产品
解决方案
定价
更多

Django日历项目:实现跨起止日期多日同步显示事件的问题

跨天事件日历渲染修改方案

问题根因

原有逻辑仅匹配事件start_time对应当天日期的记录,既没有覆盖start_time到end_time之间的跨度日期,也没有拉取跨月延伸的事件数据,导致长周期事件只能在起始日显示。
修改核心逻辑:为每个日历格子对应的自然日构建时间区间,判断事件的起止范围与当日区间是否重叠,重叠则将事件渲染到对应日期格中。

逐文件修改内容

1. 修正Models层语法错误

原有代码中get_html_url属性存在缩进错误,会导致方法无法正常挂载到Event类,修正后代码:

from django.db import models
from django.urls import reverse


class Event(models.Model):
    title = models.CharField(max_length=200)
    description = models.TextField()
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()

    @property
    def get_html_url(self):
        url = reverse('cal:event_edit', args=(self.id,))
        return f'<a href="{url}"> {self.title} </a>'

2. 核心修改:utils.py 日历渲染逻辑

调整两处核心逻辑:

  • 拉取事件时,筛选所有和当前展示月份有时间重叠的事件,避免跨月事件漏拉取
  • 渲染单日格子时,基于完整的年月日构建当日时间边界,通过区间重叠判断匹配当天需要展示的事件,不再单纯依赖start_time__day做匹配
    修改后的完整Calendar类代码:
from datetime import datetime, timedelta, date
from calendar import HTMLCalendar
from .models import Event

class Calendar(HTMLCalendar):
    def __init__(self, year=None, month=None):
        self.year = year
        self.month = month
        super(Calendar, self).__init__()

    def formatday(self, day, events):
        # 跳过日历中非当月的占位空值
        if day == 0:
            return '<td></td>'
        
        # 构建当前格子对应的完整自然日对象
        current_day = date(self.year, self.month, day)
        # 构建当日的时间边界:当日00:00 至 次日00:00
        day_start = datetime.combine(current_day, datetime.min.time())
        day_end = day_start + timedelta(days=1)

        # 筛选和当日区间存在重叠的所有事件
        events_per_day = [
            event for event in events
            if event.start_time < day_end and event.end_time >= day_start
        ]

        event_html = ''
        for event in events_per_day:
            event_html += f'<li> {event.get_html_url} </li>'

        return f"<td><span class='date'>{day}</span><ul> {event_html} </ul></td>"

    def formatweek(self, theweek, events):
        week_html = ''
        for d, weekday in theweek:
            week_html += self.formatday(d, events)
        return f'<tr> {week_html} </tr>'

    def formatmonth(self, withyear=True):
        # 计算当前展示月份的时间边界
        month_start = date(self.year, self.month, 1)
        if self.month == 12:
            month_end = date(self.year + 1, 1, 1)
        else:
            month_end = date(self.year, self.month + 1, 1)

        # 拉取所有和当前月份有时间重叠的事件,避免跨月事件漏显示
        events = Event.objects.filter(
            start_time__lt=datetime.combine(month_end, datetime.min.time()),
            end_time__gte=datetime.combine(month_start, datetime.min.time())
        )

        cal_html = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n'
        cal_html += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n'
        cal_html += f'{self.formatweekheader()}\n'
        for week in self.monthdays2calendar(self.year, self.month):
            cal_html += f'{self.formatweek(week, events)}\n'
        return cal_html

3. 修正Views层类型兼容问题

原有get_date方法未传参数时返回datetime类型,和后续月份跳转方法中的date类型操作存在兼容问题,统一返回date对象即可:

def get_date(req_day):
    if req_day:
        year, month = (int(x) for x in req_day.split('-'))
        return date(year, month, day=1)
    # 统一返回date类型,避免类型不匹配报错
    return date.today()

效果验证

按照示例场景设置事件start_time=2020-12-20、end_time=2020-12-24后,12月日历的20、21、22、23、24号格子都会自动渲染该事件;若事件跨月,比如设置start_time=2020-12-30、end_time=2021-01-03,查看12月时会在30、31号显示事件,查看1月时会在1、2、3号显示事件,不存在漏显示问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 17:36:02