[1.11.x] Fixed #28209 -- Made date-based generic views return a 404 rather than crash when given an out of range date.

Backport of c2eea61dff from master
This commit is contained in:
Adit Biswas 2017-05-16 00:26:30 +05:30 committed by Tim Graham
parent 4112bce442
commit 4e675999d5
3 changed files with 26 additions and 3 deletions

View File

@ -66,7 +66,10 @@ class YearMixin(object):
The interval is defined by start date <= item date < next start date.
"""
return date.replace(year=date.year + 1, month=1, day=1)
try:
return date.replace(year=date.year + 1, month=1, day=1)
except ValueError:
raise Http404(_("Date out of range"))
def _get_current_year(self, date):
"""
@ -123,7 +126,10 @@ class MonthMixin(object):
The interval is defined by start date <= item date < next start date.
"""
if date.month == 12:
return date.replace(year=date.year + 1, month=1, day=1)
try:
return date.replace(year=date.year + 1, month=1, day=1)
except ValueError:
raise Http404(_("Date out of range"))
else:
return date.replace(month=date.month + 1, day=1)
@ -237,7 +243,10 @@ class WeekMixin(object):
The interval is defined by start date <= item date < next start date.
"""
return date + datetime.timedelta(days=7 - self._get_weekday(date))
try:
return date + datetime.timedelta(days=7 - self._get_weekday(date))
except OverflowError:
raise Http404(_("Date out of range"))
def _get_current_week(self, date):
"""

View File

@ -44,3 +44,6 @@ Bugfixes
invalid SQL (:ticket:`28199`).
* Corrected detection of GDAL 2.1 on Windows (:ticket:`28181`).
* Made date-based generic views return a 404 rather than crash when given an
out of range date (:ticket:`28209`).

View File

@ -664,6 +664,17 @@ class DateDetailViewTests(TestDataMixin, TestCase):
self.assertEqual(res.context['book'], b)
self.assertTemplateUsed(res, 'generic_views/book_detail.html')
def test_year_out_of_range(self):
urls = [
'/dates/books/9999/',
'/dates/books/9999/12/',
'/dates/books/9999/week/52/',
]
for url in urls:
res = self.client.get(url)
self.assertEqual(res.status_code, 404)
self.assertEqual(res.context['exception'], 'Date out of range')
def test_invalid_url(self):
with self.assertRaises(AttributeError):
self.client.get("/dates/books/2008/oct/01/nopk/")