Skip to content

Commit

Permalink
DateField to_representation can handle str and empty values. Fixes en…
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryan Allen committed Apr 24, 2015
1 parent 3113e8e commit cbea03c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
6 changes: 6 additions & 0 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,6 +925,9 @@ def to_internal_value(self, value):
self.fail('invalid', format=humanized_format)

def to_representation(self, value):
if not value:
return None

if self.format is None:
return value

Expand All @@ -938,7 +941,10 @@ def to_representation(self, value):
)

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)


Expand Down
5 changes: 4 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down

0 comments on commit cbea03c

Please sign in to comment.