diff --git a/django/forms/fields.py b/django/forms/fields.py index cca2091ffa..09e20617ad 100644 --- a/django/forms/fields.py +++ b/django/forms/fields.py @@ -514,7 +514,8 @@ class DurationField(Field): } def prepare_value(self, value): - return duration_string(value) + if isinstance(value, datetime.timedelta): + return duration_string(value) def to_python(self, value): if value in self.empty_values: diff --git a/tests/forms_tests/tests/test_fields.py b/tests/forms_tests/tests/test_fields.py index 1474698118..5f44811b93 100644 --- a/tests/forms_tests/tests/test_fields.py +++ b/tests/forms_tests/tests/test_fields.py @@ -48,6 +48,7 @@ from django.test import SimpleTestCase, ignore_warnings from django.utils import formats, six, translation from django.utils._os import upath from django.utils.deprecation import RemovedInDjango20Warning +from django.utils.duration import duration_string try: from PIL import Image @@ -614,7 +615,7 @@ class FieldsTests(SimpleTestCase): d = datetime.datetime(2006, 9, 17, 14, 30, 0) self.assertFalse(f.has_changed(d, '2006 09 17 2:30 PM')) - # RegexField ################################################################## + # DurationField ########################################################### def test_durationfield_1(self): f = DurationField() @@ -642,6 +643,14 @@ class FieldsTests(SimpleTestCase): str(f['duration']) ) + def test_durationfield_prepare_value(self): + field = DurationField() + td = datetime.timedelta(minutes=15, seconds=30) + self.assertEqual(field.prepare_value(td), duration_string(td)) + self.assertIsNone(field.prepare_value(None)) + + # RegexField ################################################################## + def test_regexfield_1(self): f = RegexField('^[0-9][A-F][0-9]$') self.assertEqual('2A2', f.clean('2A2'))