Fix bug for not existent or ambiguous datetime during native to aware conversion in timezone with DST.

Ref: #4986
This commit is contained in:
Sergey Petrunin 2017-03-18 22:43:08 -04:00
parent 1ee54fb85c
commit d4726dab81
2 changed files with 8 additions and 6 deletions

View File

@ -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):
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

View File

@ -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'))