How do I paginate WeekArchiveView?

徘徊边缘 提交于 2019-12-07 14:24:39

问题


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.


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/7665013/how-do-i-paginate-weekarchiveview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!