From b4274ff2c6c6f476c0e6c563fac45768fff9b479 Mon Sep 17 00:00:00 2001 From: Simon Kelly Date: Wed, 24 Jan 2024 13:28:10 +0200 Subject: [PATCH 1/2] use django timezone util to avoid runtime warnings Depending on the Django settings the DateTimeField expects either a naive or non-naive datetime object. A runtime warning is emitted if the field receives a value it is not expecting. Using `django.utils.timezone.now` solves this since it returns the datetime with the correct TZ value. --- field_audit/models.py | 3 ++- tests/test_models.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/field_audit/models.py b/field_audit/models.py index b5381ae..dd9edbd 100644 --- a/field_audit/models.py +++ b/field_audit/models.py @@ -6,6 +6,7 @@ from django.conf import settings from django.db import models, transaction from django.db.models import Expression +from django.utils import timezone from .const import BOOTSTRAP_BATCH_SIZE from .utils import class_import_helper @@ -197,7 +198,7 @@ def get_date(): This is the "getter" for default values of the ``AuditEvent.event_date`` field. """ - return datetime.utcnow() + return timezone.now() class AuditEvent(models.Model): diff --git a/tests/test_models.py b/tests/test_models.py index 870d7af..021caa8 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -10,6 +10,7 @@ from django.db.models import Case, When, Value from django.db.utils import IntegrityError, DatabaseError from django.test import TestCase, override_settings +from django.utils import timezone from field_audit.auditors import audit_dispatcher from field_audit.const import BOOTSTRAP_BATCH_SIZE @@ -295,7 +296,7 @@ def test_get_manager_uses_default_if_no_setting(self): def test_get_date(self): then = get_date() self.assertLess( - datetime.utcnow() - then, + timezone.now() - then, timedelta(seconds=1), ) From 195e9be317686288601bcccccad14b7c6721423f Mon Sep 17 00:00:00 2001 From: Simon Kelly Date: Wed, 24 Jan 2024 14:18:19 +0200 Subject: [PATCH 2/2] remove unused import --- field_audit/models.py | 1 - tests/test_models.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/field_audit/models.py b/field_audit/models.py index dd9edbd..5a8ec1d 100644 --- a/field_audit/models.py +++ b/field_audit/models.py @@ -1,4 +1,3 @@ -from datetime import datetime from enum import Enum from functools import wraps from itertools import islice diff --git a/tests/test_models.py b/tests/test_models.py index 021caa8..f62df12 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,5 +1,5 @@ from contextlib import ContextDecorator -from datetime import datetime, timedelta +from datetime import timedelta from enum import Enum from unittest.mock import ANY, Mock, patch