How do I paginate WeekArchiveView?

2019-05-14 22:06发布

In continuation of my struggle with WeekArchiveView, how do I paginate it by week?

All I want is:

  • to know if there is next / previous week available;
  • in case there is, provide a link in the template.

I'd like it to also skip empty weeks.

The source shows get_next_day / get_prev_day and get_next_month / get_prev_month are available, but nothing for weeks.

2条回答
beautiful°
2楼-- · 2019-05-14 22:42

Taking chrisdpratt's code as basis, I created a class that provides the template with next_week and 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

This works perfect.

查看更多
小情绪 Triste *
3楼-- · 2019-05-14 22:44

That is definitely interesting. Sure enough MonthMixin includes get_next_month/get_prev_month methods, and DayMixin includes get_next_day/get_prev_day methods. However, both YearMixin and WeekMixin have no functional equivalent in their definitions. Seems like a bit of an oversight on the Django team's part.

I think your best bet is to subclass either WeekArchiveView or BaseWeekArchiveView (if you may eventually want to change up the response format and don't want to have to re-implement your methods) and add your own get_next_week/get_prev_week methods. Then have your view inherit from your subclass instead. A simple modification of DayMixins methods should be sufficient.

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)
查看更多
登录 后发表回答