2
0
Эх сурвалжийг харах

Fixed #9762 -- Made DateFormat.r() locale-independent.

Thanks to Antonio Melé for the original report all those years ago
and to all the contributors who helped along the way.
Baptiste Mispelon 5 жил өмнө
parent
commit
8929afb8ec

+ 9 - 2
django/utils/dateformat.py

@@ -13,12 +13,15 @@ Usage:
 import calendar
 import datetime
 import time
+from email.utils import format_datetime as format_datetime_rfc5322
 
 from django.utils.dates import (
     MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR,
 )
 from django.utils.regex_helper import _lazy_re_compile
-from django.utils.timezone import get_default_timezone, is_aware, is_naive
+from django.utils.timezone import (
+    get_default_timezone, is_aware, is_naive, make_aware,
+)
 from django.utils.translation import gettext as _
 
 re_formatchars = _lazy_re_compile(r'(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])')
@@ -283,7 +286,11 @@ class DateFormat(TimeFormat):
                 "The format for date objects may not contain time-related "
                 "format specifiers (found 'r')."
             )
-        return self.format('D, j M Y H:i:s O')
+        if is_naive(self.data):
+            dt = make_aware(self.data, timezone=self.timezone)
+        else:
+            dt = self.data
+        return format_datetime_rfc5322(dt)
 
     def S(self):
         "English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'"

+ 10 - 1
tests/utils_tests/test_dateformat.py

@@ -131,7 +131,7 @@ class DateFormatTests(SimpleTestCase):
 
         if TZ_SUPPORT:
             self.assertEqual(dateformat.format(my_birthday, 'O'), '+0100')
-            self.assertEqual(dateformat.format(my_birthday, 'r'), 'Sun, 8 Jul 1979 22:00:00 +0100')
+            self.assertEqual(dateformat.format(my_birthday, 'r'), 'Sun, 08 Jul 1979 22:00:00 +0100')
             self.assertEqual(dateformat.format(my_birthday, 'T'), 'CET')
             self.assertEqual(dateformat.format(my_birthday, 'e'), '')
             self.assertEqual(dateformat.format(aware_dt, 'e'), '-0330')
@@ -156,3 +156,12 @@ class DateFormatTests(SimpleTestCase):
             )
             with self.assertRaisesMessage(TypeError, msg):
                 dateformat.format(my_birthday, specifier)
+
+    def test_r_format_with_non_en_locale(self):
+        # Changing the locale doesn't change the "r" format.
+        dt = datetime(1979, 7, 8, 22, 00)
+        with translation.override('fr'):
+            self.assertEqual(
+                dateformat.format(dt, 'r'),
+                'Sun, 08 Jul 1979 22:00:00 +0100',
+            )