From ef19aec2caab1ad246fd48ba1cf7c02e05706a5d Mon Sep 17 00:00:00 2001 From: kjpc-tech Date: Thu, 14 May 2020 16:56:21 -0600 Subject: [PATCH] [3.1.x] Fixed #31590 -- Fixed ModelAdmin.date_hierarchy crash with an empty QuerySet. Regression in 55cdf6c52db07f29128741b8734a523ed042e465. Backport of 099bce1bf0b9802b7159beb9260b9b9e344bf497 from master --- django/contrib/admin/templatetags/admin_list.py | 10 +++++----- tests/admin_views/tests.py | 5 +++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/django/contrib/admin/templatetags/admin_list.py b/django/contrib/admin/templatetags/admin_list.py index 2b48f09f219..55565579aee 100644 --- a/django/contrib/admin/templatetags/admin_list.py +++ b/django/contrib/admin/templatetags/admin_list.py @@ -380,12 +380,12 @@ def date_hierarchy(cl): # select appropriate start level date_range = cl.queryset.aggregate(first=models.Min(field_name), last=models.Max(field_name)) - if dates_or_datetimes == 'datetimes': - date_range = { - k: timezone.localtime(v) if timezone.is_aware(v) else v - for k, v in date_range.items() - } if date_range['first'] and date_range['last']: + if dates_or_datetimes == 'datetimes': + date_range = { + k: timezone.localtime(v) if timezone.is_aware(v) else v + for k, v in date_range.items() + } if date_range['first'].year == date_range['last'].year: year_lookup = date_range['first'].year if date_range['first'].month == date_range['last'].month: diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py index eb6f009f032..4d307486f13 100644 --- a/tests/admin_views/tests.py +++ b/tests/admin_views/tests.py @@ -969,6 +969,11 @@ class AdminViewBasicTest(AdminViewBasicTestCase): self.assertEqual(response.context['site_url'], '/my-site-url/') self.assertContains(response, 'View site') + def test_date_hierarchy_empty_queryset(self): + self.assertIs(Question.objects.exists(), False) + response = self.client.get(reverse('admin:admin_views_answer2_changelist')) + self.assertEqual(response.status_code, 200) + @override_settings(TIME_ZONE='America/Sao_Paulo', USE_TZ=True) def test_date_hierarchy_timezone_dst(self): # This datetime doesn't exist in this timezone due to DST.