我的django视图中有一个日历。我正在尝试返回一个字典,其中包含开始日期和结束日期之间的日期列表。
目前,我只能返回开始日期或结束日期的列表。我需要这些以及中间的所有日子才能成为字典的一部分。
class HolidayCalendar(HTMLCalendar):
def __init__(self, holiday):
super(HolidayCalendar, self).__init__()
self.holiday = self.holiday_days(holiday)
#some formatting
def holiday_days(self, holiday):
#don't actually know how this works....
field = lambda holiday: holiday.start_date.day
# field = lambda holiday: holiday.end_date.day
return dict(
[(day, list(items)) for day, items in groupby(holiday, field)]
)
说实话,我根本不完全理解这一点...... 这是调用此视图的视图:
def holiday(request):
#some code
date_today = datetime.now()
year = date_today.year
month = date_today.month
my_holidays = Holiday.objects.order_by('start_date').filter(
Q(start_date__year=year, start_date__month=month) | Q(end_date__year=year, end_date__month=month)
)
cal = HolidayCalendar(my_holidays).formatmonth(year, month)
#form stuff
context = {
"holidayform": holidayform,
"calendar": mark_safe(cal),
}
return render(request, "tande/calendar.html", context)
谢谢!
答案 0 :(得分:1)
有了开始日期和结束日期,您可以向前者添加1天timedelta
,直到达到后者为止。像这样:
day_delta = timedelta(1,0,0)
next = start_date
days = []
while (end_date - next) < day_delta:
next = next + day
days.append(next)
现在days
将列出start_date
和end_date
答案 1 :(得分:0)
这是我的解决方案,我最后不需要字典我只是使用了一个列表:
class HolidayCalendar(HTMLCalendar):
def __init__(self, holiday):
super(HolidayCalendar, self).__init__()
self.holiday = self.holiday_days(holiday)
def holiday_days(self, holiday):
day_delta = timedelta(1,0,0)
holidays = Holiday.objects.all()
days = []
for balloon in holidays:
next = balloon.start_date
end = balloon.end_date
while (end - next) > day_delta:
next = next + day_delta
days.append(next)
start_day = balloon.start_date
days.append(start_day)
days.append(end)
holiday = []
for purple in days:
pink = purple.day
holiday.append(pink)
return holiday