Skip to content

Commit

Permalink
Fixed problem when setting django.db.models.functions.Now() in `Dat…
Browse files Browse the repository at this point in the history
…eTimeField` (#635)
  • Loading branch information
hramezani authored Apr 29, 2024
1 parent 1569051 commit a652eeb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion auditlog/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions auditlog_tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down

0 comments on commit a652eeb

Please sign in to comment.