Skip to content

Commit da535d3

Browse files
Fixed active timezone handling for non ISO8601 datetimes. (#5833)
* Add failing test for to_representation with explicit default timezone See discussion here: #5435 (comment) * Always run enforce_timezone
1 parent 2854679 commit da535d3

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

rest_framework/fields.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1212,8 +1212,9 @@ def to_representation(self, value):
12121212
if output_format is None or isinstance(value, six.string_types):
12131213
return value
12141214

1215+
value = self.enforce_timezone(value)
1216+
12151217
if output_format.lower() == ISO_8601:
1216-
value = self.enforce_timezone(value)
12171218
value = value.isoformat()
12181219
if value.endswith('+00:00'):
12191220
value = value[:-6] + 'Z'

tests/test_fields.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from django.http import QueryDict
1010
from django.test import TestCase, override_settings
1111
from django.utils import six
12-
from django.utils.timezone import activate, deactivate, utc
12+
from django.utils.timezone import activate, deactivate, override, utc
1313

1414
import rest_framework
1515
from rest_framework import compat, serializers
@@ -1296,6 +1296,27 @@ def test_current_timezone(self):
12961296
assert self.field.default_timezone() == utc
12971297

12981298

1299+
@pytest.mark.skipif(pytz is None, reason='pytz not installed')
1300+
@override_settings(TIME_ZONE='UTC', USE_TZ=True)
1301+
class TestCustomTimezoneForDateTimeField(TestCase):
1302+
1303+
@classmethod
1304+
def setup_class(cls):
1305+
cls.kolkata = pytz.timezone('Asia/Kolkata')
1306+
cls.date_format = '%d/%m/%Y %H:%M'
1307+
1308+
def test_should_render_date_time_in_default_timezone(self):
1309+
field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format)
1310+
dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=pytz.utc)
1311+
1312+
with override(self.kolkata):
1313+
rendered_date = field.to_representation(dt)
1314+
1315+
rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format)
1316+
1317+
assert rendered_date == rendered_date_in_timezone
1318+
1319+
12991320
class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
13001321
"""
13011322
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.

0 commit comments

Comments
 (0)