Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
5 changes: 4 additions & 1 deletion rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,10 @@ def render_field(self, field, parent_style):
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])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The millisecond part should be retained, as it's a valid part of the format.


if 'template' in style:
template_name = style['template']
Expand Down
18 changes: 18 additions & 0 deletions tests/test_renderers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import re
from collections.abc import MutableMapping
from datetime import datetime

import pytest
from django.core.cache import cache
Expand Down Expand Up @@ -488,6 +489,23 @@ class TestSerializer(serializers.Serializer):
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):
Expand Down
Loading