diff --git a/CHANGELOG.md b/CHANGELOG.md index 299414fe..d72444b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## Next Release +#### Fixes + +- Fixed problem when setting `django.db.models.functions.Now()` in `DateTimeField` ([#635](https://github.com/jazzband/django-auditlog/pull/635)) + ## 3.0.0 (2024-04-12) #### Fixes diff --git a/auditlog/diff.py b/auditlog/diff.py index b4294fed..0212e9f3 100644 --- a/auditlog/diff.py +++ b/auditlog/diff.py @@ -66,7 +66,11 @@ def get_field_value(obj, field): if isinstance(field, DateTimeField): # DateTimeFields are timezone-aware, so we need to convert the field # to its naive form before we can accurately compare them for changes. - value = field.to_python(getattr(obj, field.name, None)) + value = getattr(obj, field.name, None) + try: + value = field.to_python(value) + except TypeError: + return value if ( value is not None and settings.USE_TZ diff --git a/auditlog_tests/tests.py b/auditlog_tests/tests.py index 627324f4..0a682c64 100644 --- a/auditlog_tests/tests.py +++ b/auditlog_tests/tests.py @@ -17,6 +17,7 @@ from django.contrib.contenttypes.models import ContentType from django.core import management from django.db import models +from django.db.models.functions import Now from django.db.models.signals import pre_save from django.test import RequestFactory, TestCase, override_settings from django.urls import resolve, reverse @@ -1071,6 +1072,24 @@ def test_update_naive_dt(self): ) dtm.save() + def test_datetime_field_functions_now(self): + timestamp = datetime.datetime(2017, 1, 10, 15, 0, tzinfo=timezone.utc) + date = datetime.date(2017, 1, 10) + time = datetime.time(12, 0) + + dtm = DateTimeFieldModel( + label="DateTimeField model", + timestamp=timestamp, + date=date, + time=time, + naive_dt=Now(), + ) + dtm.save() + dtm.naive_dt = Now() + self.assertEqual(dtm.naive_dt, Now()) + dtm.save() + self.assertEqual(dtm.naive_dt, Now()) + class UnregisterTest(TestCase): def setUp(self):