Skip to content

Commit

Permalink
Fixed #34921 -- Fixed crash of warning for unbound naive datetimes.
Browse files Browse the repository at this point in the history
  • Loading branch information
shangxiao authored and felixxm committed Oct 22, 2023
1 parent 61cc0e6 commit b5311ee
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
9 changes: 6 additions & 3 deletions django/db/models/fields/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1595,10 +1595,13 @@ def to_python(self, value):
# local time. This won't work during DST change, but we can't
# do much about it, so we let the exceptions percolate up the
# call stack.
try:
name = f"{self.model.__name__}.{self.name}"
except AttributeError:
name = "(unbound)"
warnings.warn(
"DateTimeField %s.%s received a naive datetime "
"(%s) while time zone support is active."
% (self.model.__name__, self.name, value),
f"DateTimeField {name} received a naive datetime ({value}) while "
"time zone support is active.",
RuntimeWarning,
)
default_timezone = timezone.get_default_timezone()
Expand Down
8 changes: 8 additions & 0 deletions tests/timezones/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from django.core import serializers
from django.db import connection
from django.db.models import F, Max, Min
from django.db.models.functions import Now
from django.http import HttpRequest
from django.template import (
Context,
Expand Down Expand Up @@ -327,6 +328,13 @@ def test_datetime_from_date(self):
event = Event.objects.get()
self.assertEqual(event.dt, datetime.datetime(2011, 9, 1, tzinfo=EAT))

@requires_tz_support
def test_filter_unbound_datetime_with_naive_date(self):
dt = datetime.date(2011, 9, 1)
msg = "DateTimeField (unbound) received a naive datetime"
with self.assertWarnsMessage(RuntimeWarning, msg):
Event.objects.annotate(unbound_datetime=Now()).filter(unbound_datetime=dt)

@requires_tz_support
def test_naive_datetime_with_microsecond(self):
dt = datetime.datetime(2011, 9, 1, 13, 20, 30, 405060)
Expand Down

0 comments on commit b5311ee

Please sign in to comment.