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
This commit is contained in:
Carlton Gibson 2018-02-16 16:47:49 +01:00 committed by GitHub
parent 2854679f56
commit da535d31dd
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 24 additions and 2 deletions

View File

@ -1212,8 +1212,9 @@ class DateTimeField(Field):
if output_format is None or isinstance(value, six.string_types): if output_format is None or isinstance(value, six.string_types):
return value return value
if output_format.lower() == ISO_8601:
value = self.enforce_timezone(value) value = self.enforce_timezone(value)
if output_format.lower() == ISO_8601:
value = value.isoformat() value = value.isoformat()
if value.endswith('+00:00'): if value.endswith('+00:00'):
value = value[:-6] + 'Z' value = value[:-6] + 'Z'

View File

@ -9,7 +9,7 @@ import pytest
from django.http import QueryDict from django.http import QueryDict
from django.test import TestCase, override_settings from django.test import TestCase, override_settings
from django.utils import six 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 import rest_framework
from rest_framework import compat, serializers from rest_framework import compat, serializers
@ -1296,6 +1296,27 @@ class TestDefaultTZDateTimeField(TestCase):
assert self.field.default_timezone() == utc 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): class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues):
""" """
Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST. Invalid values for `DateTimeField` with datetime in DST shift (non-existing or ambiguous) and timezone with DST.