From d4726dab81412af779cb7fcdc7c29fc07edc4bea Mon Sep 17 00:00:00 2001 From: Sergey Petrunin Date: Sat, 18 Mar 2017 22:43:08 -0400 Subject: [PATCH] Fix bug for not existent or ambiguous datetime during native to aware conversion in timezone with DST. Ref: #4986 --- rest_framework/fields.py | 6 +++++- tests/test_fields.py | 8 +++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 5a881c772..fa6ff0bf8 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -1085,6 +1085,7 @@ class DateTimeField(Field): default_error_messages = { 'invalid': _('Datetime has wrong format. Use one of these formats instead: {format}.'), 'date': _('Expected a datetime but got a date.'), + 'make_aware': _('Datetime can not be represented in timezone "{timezone}".') } datetime_parser = datetime.datetime.strptime @@ -1105,7 +1106,10 @@ class DateTimeField(Field): field_timezone = getattr(self, 'timezone', self.default_timezone()) if (field_timezone is not None) and not timezone.is_aware(value): - return timezone.make_aware(value, field_timezone) + try: + return timezone.make_aware(value, field_timezone) + except Exception: + self.fail('make_aware', timezone=field_timezone) elif (field_timezone is None) and timezone.is_aware(value): return timezone.make_naive(value, utc) return value diff --git a/tests/test_fields.py b/tests/test_fields.py index 971e7f0e1..da4a05091 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 utc, pytz +from django.utils.timezone import pytz, utc import rest_framework from rest_framework import serializers @@ -1213,10 +1213,8 @@ class TestNaiveDayLightSavingTimeTimeZoneDateTimeField(FieldValues): """ valid_inputs = {} invalid_inputs = { - '2017-03-12T02:30:00': [ - 'Datetime can not be converted to server timezone due to NonExistentTimeError.'], - '2017-11-05T01:30:00': [ - 'Datetime can not be converted to server timezone due to AmbiguousTimeError.'] + '2017-03-12T02:30:00': ['Datetime can not be represented in timezone "America/New_York".'], + '2017-11-05T01:30:00': ['Datetime can not be represented in timezone "America/New_York".'] } outputs = {} field = serializers.DateTimeField(default_timezone=pytz.timezone('America/New_York'))