From cbea03c85b7edc3b6ff3b589127645402f9107cc Mon Sep 17 00:00:00 2001 From: Ryan Allen Date: Thu, 23 Apr 2015 19:25:22 -0500 Subject: [PATCH] DateField to_representation can handle str and empty values. Fixes #2656, #2687. --- rest_framework/fields.py | 6 ++++++ tests/test_fields.py | 5 ++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 68835bded..460645796 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -925,6 +925,9 @@ class DateField(Field): self.fail('invalid', format=humanized_format) def to_representation(self, value): + if not value: + return None + if self.format is None: return value @@ -938,7 +941,10 @@ class DateField(Field): ) if self.format.lower() == ISO_8601: + if (isinstance(value, str)): + value = datetime.datetime.strptime(value, '%Y-%m-%d').date() return value.isoformat() + return value.strftime(self.format) diff --git a/tests/test_fields.py b/tests/test_fields.py index da6bd6ceb..1531fe2ac 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -726,7 +726,10 @@ class TestDateField(FieldValues): datetime.datetime(2001, 1, 1, 12, 00): ['Expected a date but got a datetime.'], } outputs = { - datetime.date(2001, 1, 1): '2001-01-01' + datetime.date(2001, 1, 1): '2001-01-01', + '2001-01-01': '2001-01-01', + None: None, + '': None, } field = serializers.DateField()