Ticket #18323: 18323.patch

File 18323.patch, 12.5 KB (added by Aymeric Augustin, 12 years ago)
  • django/views/generic/dates.py

    diff --git a/django/views/generic/dates.py b/django/views/generic/dates.py
    index 6964624..5185d7f 100644
    a b class YearMixin(object):  
    2323        return self.year_format
    2424
    2525    def get_year(self):
    26         "Return the year for which this view should display data"
     26        """
     27        Return the year for which this view should display data.
     28        """
    2729        year = self.year
    2830        if year is None:
    2931            try:
    class YearMixin(object):  
    3537                    raise Http404(_(u"No year specified"))
    3638        return year
    3739
     40    def _get_next_year(self, date):
     41        """
     42        Return the start date of the next interval.
     43
     44        The interval is defined by start date <= item date < next start date.
     45        """
     46        return date.replace(year=date.year + 1, month=1, day=1)
     47
     48    def _get_current_year(self, date):
     49        """
     50        Return the start date of the current interval.
     51        """
     52        return date.replace(month=1, day=1)
     53
    3854
    3955class MonthMixin(object):
    4056    month_format = '%b'
    class MonthMixin(object):  
    4864        return self.month_format
    4965
    5066    def get_month(self):
    51         "Return the month for which this view should display data"
     67        """
     68        Return the month for which this view should display data.
     69        """
    5270        month = self.month
    5371        if month is None:
    5472            try:
    class MonthMixin(object):  
    6482        """
    6583        Get the next valid month.
    6684        """
    67         # next must be the first day of the next month.
    68         if date.month == 12:
    69             next = date.replace(year=date.year + 1, month=1, day=1)
    70         else:
    71             next = date.replace(month=date.month + 1, day=1)
    72         return _get_next_prev(self, next, is_previous=False, period='month')
     85        return _get_next_prev(self, date, is_previous=False, period='month')
    7386
    7487    def get_previous_month(self, date):
    7588        """
    7689        Get the previous valid month.
    7790        """
    78         # prev must be the last day of the previous month.
    79         prev = date.replace(day=1) - datetime.timedelta(days=1)
    80         return _get_next_prev(self, prev, is_previous=True, period='month')
     91        return _get_next_prev(self, date, is_previous=True, period='month')
     92
     93    def _get_next_month(self, date):
     94        """
     95        Return the start date of the next interval.
     96
     97        The interval is defined by start date <= item date < next start date.
     98        """
     99        if date.month == 12:
     100            return date.replace(year=date.year + 1, month=1, day=1)
     101        else:
     102            return date.replace(month=date.month + 1, day=1)
     103
     104    def _get_current_month(self, date):
     105        """
     106        Return the start date of the previous interval.
     107        """
     108        return date.replace(day=1)
    81109
    82110
    83111class DayMixin(object):
    class DayMixin(object):  
    92120        return self.day_format
    93121
    94122    def get_day(self):
    95         "Return the day for which this view should display data"
     123        """
     124        Return the day for which this view should display data.
     125        """
    96126        day = self.day
    97127        if day is None:
    98128            try:
    class DayMixin(object):  
    108138        """
    109139        Get the next valid day.
    110140        """
    111         next = date + datetime.timedelta(days=1)
    112         return _get_next_prev(self, next, is_previous=False, period='day')
     141        return _get_next_prev(self, date, is_previous=False, period='day')
    113142
    114143    def get_previous_day(self, date):
    115144        """
    116145        Get the previous valid day.
    117146        """
    118         prev = date - datetime.timedelta(days=1)
    119         return _get_next_prev(self, prev, is_previous=True, period='day')
     147        return _get_next_prev(self, date, is_previous=True, period='day')
     148
     149    def _get_next_day(self, date):
     150        """
     151        Return the start date of the next interval.
     152
     153        The interval is defined by start date <= item date < next start date.
     154        """
     155        return date + datetime.timedelta(days=1)
     156
     157    def _get_current_day(self, date):
     158        """
     159        Return the start date of the current interval.
     160        """
     161        return date
    120162
    121163
    122164class WeekMixin(object):
    class WeekMixin(object):  
    131173        return self.week_format
    132174
    133175    def get_week(self):
    134         "Return the week for which this view should display data"
     176        """
     177        Return the week for which this view should display data
     178        """
    135179        week = self.week
    136180        if week is None:
    137181            try:
    class WeekMixin(object):  
    147191        """
    148192        Get the next valid week.
    149193        """
    150         # next must be the first day of the next week.
    151         next = date + datetime.timedelta(days=7 - self._get_weekday(date))
    152         return _get_next_prev(self, next, is_previous=False, period='week')
     194        return _get_next_prev(self, date, is_previous=False, period='week')
    153195
    154196    def get_previous_week(self, date):
    155197        """
    156198        Get the previous valid week.
    157199        """
    158         # prev must be the last day of the previous week.
    159         prev = date - datetime.timedelta(days=self._get_weekday(date) + 1)
    160         return _get_next_prev(self, prev, is_previous=True, period='week')
     200        return _get_next_prev(self, date, is_previous=True, period='week')
     201
     202    def _get_next_week(self, date):
     203        """
     204        Return the start date of the next interval.
     205
     206        The interval is defined by start date <= item date < next start date.
     207        """
     208        return date + datetime.timedelta(days=7 - self._get_weekday(date))
     209
     210    def _get_current_week(self, date):
     211        """
     212        Return the start date of the current interval.
     213        """
     214        return date - datetime.timedelta(self._get_weekday(date))
    161215
    162216    def _get_weekday(self, date):
    163217        week_format = self.get_week_format()
    class WeekMixin(object):  
    168222        else:
    169223            raise ValueError("unknown week format: %s" % week_format)
    170224
     225
    171226class DateMixin(object):
    172227    """
    173228    Mixin class for views manipulating date-based data.
    class BaseDateListView(MultipleObjectMixin, DateMixin, View):  
    267322        paginate_by = self.get_paginate_by(qs)
    268323
    269324        if not allow_future:
    270             now = timezone.now() if self.uses_datetime_field else datetime.date.today()
     325            now = timezone.now() if self.uses_datetime_field else timezone_today()
    271326            qs = qs.filter(**{'%s__lte' % date_field: now})
    272327
    273328        if not allow_empty:
    class BaseYearArchiveView(YearMixin, BaseDateListView):  
    344399        date = _date_from_string(year, self.get_year_format())
    345400
    346401        since = self._make_date_lookup_arg(date)
    347         until = self._make_date_lookup_arg(datetime.date(date.year + 1, 1, 1))
     402        until = self._make_date_lookup_arg(self._get_next_year(date))
    348403        lookup_kwargs = {
    349404            '%s__gte' % date_field: since,
    350405            '%s__lt' % date_field: until,
    class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView):  
    392447        date = _date_from_string(year, self.get_year_format(),
    393448                                 month, self.get_month_format())
    394449
    395         # Construct a date-range lookup.
    396450        since = self._make_date_lookup_arg(date)
    397         if date.month == 12:
    398             until = self._make_date_lookup_arg(datetime.date(date.year + 1, 1, 1))
    399         else:
    400             until = self._make_date_lookup_arg(datetime.date(date.year, date.month + 1, 1))
     451        until = self._make_date_lookup_arg(self._get_next_month(date))
    401452        lookup_kwargs = {
    402453            '%s__gte' % date_field: since,
    403454            '%s__lt' % date_field: until,
    class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView):  
    442493                                 week_start, '%w',
    443494                                 week, week_format)
    444495
    445         # Construct a date-range lookup.
    446496        since = self._make_date_lookup_arg(date)
    447         until = self._make_date_lookup_arg(date + datetime.timedelta(days=7))
     497        until = self._make_date_lookup_arg(self._get_next_week(date))
    448498        lookup_kwargs = {
    449499            '%s__gte' % date_field: since,
    450500            '%s__lt' % date_field: until,
    def _date_from_string(year, year_format, month='', month_format='', day='', day_  
    585635        })
    586636
    587637
    588 def _get_next_prev(generic_view, naive_result, is_previous, period):
     638def _get_next_prev(generic_view, date, is_previous, period):
    589639    """
    590640    Helper: Get the next or the previous valid date. The idea is to allow
    591641    links on month/day views to never be 404s by never providing a date
    592642    that'll be invalid for the given view.
    593643
    594     This is a bit complicated since it handles both next and previous months
    595     and days (for MonthArchiveView and DayArchiveView); hence the coupling to generic_view.
     644    This is a bit complicated since it handles different intervals of time,
     645    hence the coupling to generic_view.
    596646
    597647    However in essence the logic comes down to:
    598648
    599649        * If allow_empty and allow_future are both true, this is easy: just
    600           return the naive result (just the next/previous day or month,
     650          return the naive result (just the next/previous day/week/month,
    601651          reguardless of object existence.)
    602652
    603         * If allow_empty is true, allow_future is false, and the naive month
     653        * If allow_empty is true, allow_future is false, and the naive result
    604654          isn't in the future, then return it; otherwise return None.
    605655
    606656        * If allow_empty is false and allow_future is true, return the next
    def _get_next_prev(generic_view, naive_result, is_previous, period):  
    616666    allow_empty = generic_view.get_allow_empty()
    617667    allow_future = generic_view.get_allow_future()
    618668
    619     # If allow_empty is True the naive value will be valid
     669    get_current = getattr(generic_view, '_get_current_%s' % period)
     670    get_next = getattr(generic_view, '_get_next_%s' % period)
     671
     672    # Bounds of the current interval
     673    start, end = get_current(date), get_next(date)
     674
     675    # If allow_empty is True the naive result will be valid
    620676    if allow_empty:
    621         result = naive_result
     677        if is_previous:
     678            result = get_current(start - datetime.timedelta(days=1))
     679        else:
     680            result = end
    622681
    623682    # Otherwise, we'll need to go to the database to look for an object
    624683    # whose date_field is at least (greater than/less than) the given
    def _get_next_prev(generic_view, naive_result, is_previous, period):  
    627686        # Construct a lookup and an ordering depending on whether we're doing
    628687        # a previous date or a next date lookup.
    629688        if is_previous:
    630             lookup = {'%s__lte' % date_field: generic_view._make_date_lookup_arg(naive_result)}
     689            lookup = {'%s__lt' % date_field: generic_view._make_date_lookup_arg(start)}
    631690            ordering = '-%s' % date_field
    632691        else:
    633             lookup = {'%s__gte' % date_field: generic_view._make_date_lookup_arg(naive_result)}
     692            lookup = {'%s__gte' % date_field: generic_view._make_date_lookup_arg(end)}
    634693            ordering = date_field
    635694
    636695        qs = generic_view.get_queryset().filter(**lookup).order_by(ordering)
    def _get_next_prev(generic_view, naive_result, is_previous, period):  
    640699        try:
    641700            result = getattr(qs[0], date_field)
    642701        except IndexError:
    643             result = None
     702            return None
    644703
    645     # Convert datetimes to a dates
    646     if result and generic_view.uses_datetime_field:
     704    # Check against future dates.
     705    now = timezone.now() if generic_view.uses_datetime_field else timezone_today()
     706    if not allow_future and result > now:
     707        return None
     708
     709    # Convert datetimes to dates
     710    if generic_view.uses_datetime_field:
    647711        if settings.USE_TZ:
    648712            result = timezone.localtime(result)
    649713        result = result.date()
    650714
    651     if result:
    652         if period == 'month':
    653             # first day of the month
    654             result = result.replace(day=1)
    655         elif period == 'week':
    656             # monday of the week
    657             result = result - datetime.timedelta(days=generic_view._get_weekday(result))
    658         elif period != 'day':
    659             raise ValueError('invalid period: %s' % period)
     715    return get_current(result)
    660716
    661     # Check against future dates.
    662     if result and (allow_future or result < datetime.date.today()):
    663         return result
     717
     718def timezone_today():
     719    """
     720    Return the current date in the current time zone.
     721    """
     722    if settings.USE_TZ:
     723        return timezone.localtime(timezone.now()).date()
    664724    else:
    665         return None
     725        return datetime.date.today()
Back to Top