继续我的斗争,我WeekArchiveView如何按周对它进行分页?
我想要的是:
- 知道是否有下周/上周可用;
- 如果有,请在模板中提供链接。
我希望它也能跳过空旷的几周。
源显示get_next_day/get_prev_day和get_next_month/get_prev_month可用,但数周内都没有。
继续我的斗争,我WeekArchiveView如何按周对它进行分页?
我想要的是:
我希望它也能跳过空旷的几周。
源显示get_next_day/get_prev_day和get_next_month/get_prev_month可用,但数周内都没有。
这绝对很有趣。果然是MonthMixinincludes get_next_month/ get_prev_monthmethods,还有DayMixinincludes get_next_day/ get_prev_daymethods。然而, YearMixin 和 WeekMixin 在它们的定义中没有等效的功能。似乎对 Django 团队来说有点疏忽。
我认为您最好的选择是继承 WeekArchiveView 或 BaseWeekArchiveView (如果您最终可能想要更改响应格式并且不想重新实现您的方法)并添加您自己的get_next_week/get_prev_week方法。然后让您的视图从您的子类继承。对 s 方法进行简单的修改DayMixin就足够了。
def get_next_week(self, date):
"""
Get the next valid week.
"""
next = date + datetime.timedelta(days=7)
return _get_next_prev_month(self, next, is_previous=False, use_first_day=False)
def get_previous_week(self, date):
"""
Get the previous valid week.
"""
prev = date - datetime.timedelta(days=7)
return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False)
以chrisdpratt 的代码为基础,我创建了一个类,该类为模板提供next_week和previous_week:
class BetterWeekArchiveView(WeekArchiveView):
def get_next_week(self, date):
"""
Get the next valid week.
"""
next = date + timedelta(days=7)
return _get_next_prev_month(self, next, is_previous=False, use_first_day=False)
def get_previous_week(self, date):
"""
Get the previous valid week.
"""
prev = date - timedelta(days=7)
return _get_next_prev_month(self, prev, is_previous=True, use_first_day=False)
def get_dated_items(self):
"""
Return (date_list, items, extra_context) for this request.
Inject next_week and previous_week into extra_context.
"""
result = super(BetterWeekArchiveView, self).get_dated_items()
extra_context = result[2]
date = extra_context['week']
extra_context.update({
'next_week': self.get_next_week(date),
'previous_week': self.get_previous_week(date),
})
return result
这很完美。