Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ def render_field(self, field, parent_style):
except AttributeError:
format_ = api_settings.DATETIME_FORMAT

if format_ is not None:
if format_ is not None and field.value not in (None, ''):
# field.value is expected to be a string
# https://www.django-rest-framework.org/api-guide/fields/#datetimefield
field_value = field.value
Expand All @@ -358,10 +358,11 @@ def render_field(self, field, parent_style):
else datetime.datetime.strptime(field_value, format_)
)

# The format of an input type="datetime-local" is "yyyy-MM-ddThh:mm"
# followed by optional ":ss" or ":ss.SSS", so keep only the first three
# digits of milliseconds to avoid browser console error.
field.value = field.value.replace(tzinfo=None).isoformat(timespec="milliseconds")
if isinstance(field.value, datetime.datetime):
# The format of an input type="datetime-local" is "yyyy-MM-ddThh:mm"
# followed by optional ":ss" or ":ss.SSS", so keep only the first three
# digits of milliseconds to avoid browser console error.
field.value = field.value.replace(tzinfo=None).isoformat(timespec="milliseconds")

if 'template' in style:
template_name = style['template']
Expand Down
16 changes: 16 additions & 0 deletions tests/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -566,6 +566,22 @@ def test_datetime_field_rendering_timezone_aware_datetime(self):
"2024-12-23T09:55:30.345" # Rendered in -06:00
)

def test_datetime_field_rendering_empty_string_raises_no_error(self):
"""
Regression test for #9927 (issue):
Ensures that an empty string value doesn't cause a ValueError
when the HTMLFormRenderer tries to parse it via fromisoformat.
"""
self._assert_datetime_rendering("", "")

def test_datetime_field_rendering_none_value_raises_no_error(self):
"""
Additional regression coverage for #9927:
Ensures that a None value, which is converted to an empty string
by as_form_field(), doesn't cause a ValueError when rendered.
"""
self._assert_datetime_rendering(None, "")


class TestHTMLFormRenderer(TestCase):
def setUp(self):
Expand Down
Loading