diff options
| author | David Sanders <shang.xiao.sanders@gmail.com> | 2023-10-22 18:41:30 +1100 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2023-10-22 14:26:38 +0200 |
| commit | b5311ee23219cfb676e2e67667ecba1e5d363aa0 (patch) | |
| tree | 4eee9fd36023830a9b9848af7dbb9093e61dd670 | |
| parent | 61cc0e6f2c5115415e70e0a7eddd59b7c2aed40d (diff) | |
Fixed #34921 -- Fixed crash of warning for unbound naive datetimes.
| -rw-r--r-- | django/db/models/fields/__init__.py | 9 | ||||
| -rw-r--r-- | tests/timezones/tests.py | 8 |
2 files changed, 14 insertions, 3 deletions
diff --git a/django/db/models/fields/__init__.py b/django/db/models/fields/__init__.py index 5f8f59d69f..f15b5856bf 100644 --- a/django/db/models/fields/__init__.py +++ b/django/db/models/fields/__init__.py @@ -1595,10 +1595,13 @@ class DateTimeField(DateField): # 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() diff --git a/tests/timezones/tests.py b/tests/timezones/tests.py index 433c921cd3..c45f078ef6 100644 --- a/tests/timezones/tests.py +++ b/tests/timezones/tests.py @@ -10,6 +10,7 @@ from django.contrib.auth.models import User 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, @@ -328,6 +329,13 @@ class NewDatabaseTests(TestCase): 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) with self.assertWarnsMessage(RuntimeWarning, self.naive_warning): |
