Fixed #5363 -- HTML5 datetime-local valid format HTMLFormRenderer

This commit is contained in:
Marcelo Galigniana 2024-04-04 16:23:19 -03:00
parent 085b7e166b
commit c967a6f4d8
2 changed files with 22 additions and 1 deletions

View File

@ -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']

View File

@ -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(
'<input name="appointment" class="form-control" type="datetime-local" value="2024-12-24T00:55:30">',
rendered
)
class TestHTMLFormRenderer(TestCase):
def setUp(self):
class TestSerializer(serializers.Serializer):