From 45c7acdc507d26451f3c3f22b5d60bdd6d572cfc Mon Sep 17 00:00:00 2001 From: Marko Benko Date: Sun, 3 Apr 2016 19:31:35 +0200 Subject: [PATCH] Fixed #26281 -- Added a helpful error message for an invalid format specifier to dateformat.format(). --- django/template/defaultfilters.py | 4 ++-- django/utils/dateformat.py | 5 +++++ tests/utils_tests/test_dateformat.py | 11 +++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index fb473ec99d..448a3f753a 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -767,10 +767,10 @@ def time(value, arg=None): return '' try: return formats.time_format(value, arg) - except AttributeError: + except (AttributeError, TypeError): try: return time_format(value, arg) - except AttributeError: + except (AttributeError, TypeError): return '' diff --git a/django/utils/dateformat.py b/django/utils/dateformat.py index ea55eaaf9d..f82e0098b8 100644 --- a/django/utils/dateformat.py +++ b/django/utils/dateformat.py @@ -34,6 +34,11 @@ class Formatter(object): pieces = [] for i, piece in enumerate(re_formatchars.split(force_text(formatstr))): if i % 2: + if type(self.data) is datetime.date and hasattr(TimeFormat, piece): + raise TypeError( + "The format for date objects may not contain " + "time-related format specifiers (found '%s')." % piece + ) pieces.append(force_text(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r'\1', piece)) diff --git a/tests/utils_tests/test_dateformat.py b/tests/utils_tests/test_dateformat.py index 143fbee4e3..bda69fb4cd 100644 --- a/tests/utils_tests/test_dateformat.py +++ b/tests/utils_tests/test_dateformat.py @@ -153,3 +153,14 @@ class DateFormatTests(SimpleTestCase): # Ticket #16924 -- We don't need timezone support to test this self.assertEqual(dateformat.format(aware_dt, 'O'), '-0330') + + def test_invalid_time_format_specifiers(self): + my_birthday = date(1984, 8, 7) + + for specifier in ['a', 'A', 'f', 'g', 'G', 'h', 'H', 'i', 'P', 's', 'u']: + msg = ( + "The format for date objects may not contain time-related " + "format specifiers (found '%s')." % specifier + ) + with self.assertRaisesMessage(TypeError, msg): + dateformat.format(my_birthday, specifier)