Skip to content
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
8 changes: 6 additions & 2 deletions rest_framework/renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -342,8 +342,12 @@ def render_field(self, field, parent_style):
# Get a clone of the field with text-only value representation.
field = field.as_form_field()

if style.get('input_type') == 'datetime-local' and isinstance(field.value, str):
field.value = field.value.rstrip('Z')
if style.get('input_type') == 'datetime-local':
# 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.
datetime_value = field._field.parent.validated_data.get(field.field_name)
field.value = datetime_value.replace(tzinfo=None).isoformat(timespec="milliseconds").rstrip('Z')
Comment on lines +349 to +350
Copy link
Contributor Author

Choose a reason for hiding this comment

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

It was harder than I thought!

Let me know if this is the correct way to get the datetime value.

Copy link
Collaborator

Choose a reason for hiding this comment

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

I'm not sure. Is it guaranteed that there is always a parent?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I don't have a depth knowledge of the framework, but the only place I found where it can be None is:

# These are set up by `.bind()` when the field is added to a serializer.

A DRF field can be outside of a seralizer?


Comment on lines +350 to 351
Copy link
Preview

Copilot AI Sep 21, 2025

Choose a reason for hiding this comment

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

This code will raise an AttributeError if datetime_value is None or if validated_data doesn't contain the field. The original code checked isinstance(field.value, str) which provided a safety check. Consider adding a null check or fallback to the original field.value when datetime_value is None.

Suggested change
field.value = datetime_value.replace(tzinfo=None).isoformat(timespec="milliseconds").rstrip('Z')
if datetime_value is not None:
field.value = datetime_value.replace(tzinfo=None).isoformat(timespec="milliseconds").rstrip('Z')
# Fallback: if datetime_value is None, keep field.value as is (original behavior)

Copilot uses AI. Check for mistakes.

Copy link
Collaborator

Choose a reason for hiding this comment

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

@mgaligniana please cross check this suggestion, and come up with a better solution if possible

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Perfect! I'll do, thanks!

if 'template' in style:
template_name = style['template']
Expand Down
84 changes: 84 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,89 @@ class TestSerializer(serializers.Serializer):
assert rendered == ''


class TestDateTimeFieldHTMLFormRender(TestCase):
Copy link
Collaborator

Choose a reason for hiding this comment

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

It would be nice to add a couple of test cases with some non-naive datetimes, with a timezone specified. Could try with UTC and another timezone where the offset is non-zero

Copy link
Contributor Author

@mgaligniana mgaligniana Sep 7, 2025

Choose a reason for hiding this comment

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

Thank you!

So I've added a docstring to let know that config variables are set in

USE_TZ=True
TIME_ZONE='America/Chicago'

And added a fourth test where @override_settings(TIME_ZONE='UTC', USE_TZ=True)

Is that correct?

"""
Default USE_TZ is True.
Default TIME_ZONE is 'America/Chicago'.
"""

def test_datetime_field_rendering_milliseconds(self):
class TestSerializer(serializers.Serializer):
appointment = serializers.DateTimeField()

appointment = datetime(2024, 12, 24, 0, 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.345">',
rendered
)

def test_datetime_field_rendering_no_milliseconds(self):
class TestSerializer(serializers.Serializer):
appointment = serializers.DateTimeField()

appointment = datetime(2024, 12, 24, 0, 55, 30, 0)
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.000">',
rendered
)

def test_datetime_field_rendering_no_seconds_and_no_milliseconds(self):
class TestSerializer(serializers.Serializer):
appointment = serializers.DateTimeField()

appointment = datetime(2024, 12, 24, 0, 55, 0, 0)
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:00.000">',
rendered
)

def test_datetime_field_rendering_with_format(self):
class TestSerializer(serializers.Serializer):
appointment = serializers.DateTimeField(format='%a %d %b %Y, %I:%M%p')

appointment = datetime(2024, 12, 24, 0, 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.345">',
rendered
)

@override_settings(TIME_ZONE='UTC', USE_TZ=True)
def test_datetime_field_utc(self):
class TestSerializer(serializers.Serializer):
appointment = serializers.DateTimeField()

appointment = datetime(2024, 12, 24, 0, 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.345">',
rendered
)


class TestHTMLFormRenderer(TestCase):
def setUp(self):
class TestSerializer(serializers.Serializer):
Expand Down