From da535d31dd93dbb1d650e2e92bd0910ca8eb4ea4 Mon Sep 17 00:00:00 2001 From: Carlton Gibson Date: Fri, 16 Feb 2018 16:47:49 +0100 Subject: [PATCH] Fixed active timezone handling for non ISO8601 datetimes. (#5833) * Add failing test for to_representation with explicit default timezone See discussion here: https://github.com/encode/django-rest-framework/pull/5435#issuecomment-364054509 * Always run enforce_timezone --- rest_framework/fields.py | 3 ++- tests/test_fields.py | 23 ++++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 51b216787..ad710b967 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1212,8 +1212,9 @@ class DateTimeField(Field): if output_format is None or isinstance(value, six.string_types): return value + value = self.enforce_timezone(value) + if output_format.lower() == ISO_8601: - value = self.enforce_timezone(value) value = value.isoformat() if value.endswith('+00:00'): value = value[:-6] + 'Z' diff --git a/tests/test_fields.py b/tests/test_fields.py index 35593a283..6a694092a 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -9,7 +9,7 @@ import pytest from django.http import QueryDict from django.test import TestCase, override_settings from django.utils import six -from django.utils.timezone import activate, deactivate, utc +from django.utils.timezone import activate, deactivate, override, utc import rest_framework from rest_framework import compat, serializers @@ -1296,6 +1296,27 @@ class TestDefaultTZDateTimeField(TestCase): assert self.field.default_timezone() == utc +@pytest.mark.skipif(pytz is None, reason='pytz not installed') +@override_settings(TIME_ZONE='UTC', USE_TZ=True) +class TestCustomTimezoneForDateTimeField(TestCase): + + @classmethod + def setup_class(cls): + cls.kolkata = pytz.timezone('Asia/Kolkata') + cls.date_format = '%d/%m/%Y %H:%M' + + def test_should_render_date_time_in_default_timezone(self): + field = serializers.DateTimeField(default_timezone=self.kolkata, format=self.date_format) + dt = datetime.datetime(2018, 2, 8, 14, 15, 16, tzinfo=pytz.utc) + + with override(self.kolkata): + rendered_date = field.to_representation(dt) + + rendered_date_in_timezone = dt.astimezone(self.kolkata).strftime(self.date_format) + + assert rendered_date == rendered_date_in_timezone + + class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): """ Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.