【问题标题】:How do I paginate WeekArchiveView?如何对 WeekArchiveView 进行分页?
【发布时间】:2011-12-01 16:12:54
【问题描述】:

继续my struggleWeekArchiveView,如何按周对其进行分页?

我想要的是:

  • 了解下周/上周是否有空;
  • 如果有,请在模板中提供链接。

我希望它也能跳过空旷的几周。

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

【问题讨论】:

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


    【解决方案1】:

    这绝对很有趣。果然MonthMixin包含get_next_month/get_prev_month方法,DayMixin包含get_next_day/get_prev_day方法。然而, YearMixin 和 WeekMixin 在它们的定义中没有等效的功能。似乎是 Django 团队的疏忽。

    我认为您最好的选择是继承 WeekArchiveView 或 BaseWeekArchiveView(如果您最终可能想要更改响应格式并且不想重新实现您的方法)并添加您自己的 get_next_week/@ 987654329@ 方法。然后让您的视图从您的子类继承。对DayMixins 方法进行简单修改就足够了。

    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)
    

    【讨论】:

    • 这对我很有帮助!谢谢。
    • 你能帮我figuring out the rest吗?我们快到了,我只是在寻找一种干净的方法来让previous_week 成为None,当在给定的一周之前没有项目时。
    • 糟糕!这是我的错。我将allow_empty 设置为True,所以这就是我得到那些空白页面的原因。再次感谢!
    【解决方案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
    

    这很完美。

    【讨论】:

      猜你喜欢
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 2010-10-21
      • 2019-06-09
      • 2016-11-06
      • 2017-12-04
      • 1970-01-01
      相关资源
      最近更新 更多