diff --git a/rest_framework/renderers.py b/rest_framework/renderers.py index db1fdd128..3a4943135 100644 --- a/rest_framework/renderers.py +++ b/rest_framework/renderers.py @@ -338,7 +338,10 @@ class HTMLFormRenderer(BaseRenderer): field = field.as_form_field() if style.get('input_type') == 'datetime-local' and isinstance(field.value, str): - field.value = field.value.rstrip('Z') + # The format of an input type="datetime-local" is "yyyy-MM-ddThh:mm" + # followed by optional ":ss" or ":ss.SSS", so remove [milli|micro]seconds + # to avoid browser error. + field.value = "".join(field.value.rstrip('Z').split(".")[:1]) if 'template' in style: template_name = style['template'] diff --git a/tests/test_renderers.py b/tests/test_renderers.py index 247737576..0e19a4586 100644 --- a/tests/test_renderers.py +++ b/tests/test_renderers.py @@ -1,5 +1,6 @@ import re from collections.abc import MutableMapping +from datetime import datetime import pytest from django.core.cache import cache @@ -488,6 +489,23 @@ class TestHiddenFieldHTMLFormRenderer(TestCase): assert rendered == '' +class TestDateTimeFieldHTMLFormRender(TestCase): + def test_datetime_field_rendering(self): + class TestSerializer(serializers.Serializer): + appointment = serializers.DateTimeField() + + appointment = datetime(2024, 12, 24, 00, 55, 30, 345678) + serializer = TestSerializer(data={"appointment": appointment}) + serializer.is_valid() + renderer = HTMLFormRenderer() + field = serializer['appointment'] + rendered = renderer.render_field(field, {}) + self.assertInHTML( + '', + rendered + ) + + class TestHTMLFormRenderer(TestCase): def setUp(self): class TestSerializer(serializers.Serializer):