Fixed problem when setting django.db.models.functions.Now() in DateTimeField (#635)

This commit is contained in:
Hasan Ramezani 2024-04-29 23:38:09 +02:00 committed by Ilya
parent 04b639fe8c
commit 43f667aaa4
3 changed files with 28 additions and 1 deletions

View file

@ -2,6 +2,10 @@
## Next Release ## 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) ## 3.0.0 (2024-04-12)
#### Fixes #### Fixes

View file

@ -66,7 +66,11 @@ def get_field_value(obj, field):
if isinstance(field, DateTimeField): if isinstance(field, DateTimeField):
# DateTimeFields are timezone-aware, so we need to convert the field # DateTimeFields are timezone-aware, so we need to convert the field
# to its naive form before we can accurately compare them for changes. # 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 ( if (
value is not None value is not None
and settings.USE_TZ and settings.USE_TZ

View file

@ -17,6 +17,7 @@ from django.contrib.auth.models import AnonymousUser, User
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.core import management from django.core import management
from django.db import models from django.db import models
from django.db.models.functions import Now
from django.db.models.signals import pre_save from django.db.models.signals import pre_save
from django.test import RequestFactory, TestCase, override_settings from django.test import RequestFactory, TestCase, override_settings
from django.urls import resolve, reverse from django.urls import resolve, reverse
@ -1061,6 +1062,24 @@ class DateTimeFieldModelTest(TestCase):
) )
dtm.save() 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): class UnregisterTest(TestCase):
def setUp(self): def setUp(self):