如何对WeekArchiveView进行分页?

时间:2011-10-05 17:10:30

标签: python django django-1.3 django-class-based-views django-pagination

继续使用my struggle WeekArchiveView,如何按周对其进行分页?

我想要的只是:

  • 知道是否有下一周/上周可用;
  • 如果有,请在模板中提供一个链接。

我希望它也可以跳过空白周。

The source显示get_next_day / get_prev_dayget_next_month / get_prev_month可用,但几周都没有。

2 个答案:

答案 0 :(得分:3)

这绝对有趣。果然MonthMixin包含get_next_month / get_prev_month方法,DayMixin包含get_next_day / get_prev_day方法。但是,YearMixin和WeekMixin的定义都没有功能等同。看起来像Django团队的一些疏忽。

我认为你最好的选择是将WeekArchiveView或BaseWeekArchiveView子类化(如果你最终可能想要改变响应格式并且不想重新实现你的方法)并添加你自己的get_next_week / get_prev_week方法。然后让您的视图继承自您的子类。对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)

答案 1 :(得分:2)

chrisdpratt's code为基础,我创建了一个为next_weekprevious_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

这很有效。