diff --git a/CHANGELOG.md b/CHANGELOG.md index 32e8637..10a4ac7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,6 +20,7 @@ via `AUDITLOG_MASK_TRACKING_FIELDS` setting. ([#702](https://github.com/jazzband - Fixed a problem when setting `Value(None)` in `JSONField` ([#646](https://github.com/jazzband/django-auditlog/pull/646)) - Fixed a problem when setting `django.db.models.functions.Now()` in `DateTimeField` ([#635](https://github.com/jazzband/django-auditlog/pull/635)) - Use the [default manager](https://docs.djangoproject.com/en/5.1/topics/db/managers/#default-managers) instead of `objects` to support custom model managers. ([#705](https://github.com/jazzband/django-auditlog/pull/705)) +- Fixed crashes when cloning objects with `pk=None` ([#707](https://github.com/jazzband/django-auditlog/pull/707)) ## 3.0.0 (2024-04-12) diff --git a/auditlog/receivers.py b/auditlog/receivers.py index 77e60f5..b1fc817 100644 --- a/auditlog/receivers.py +++ b/auditlog/receivers.py @@ -53,7 +53,7 @@ def log_update(sender, instance, **kwargs): Direct use is discouraged, connect your model through :py:func:`auditlog.registry.register` instead. """ - if not instance._state.adding: + if not instance._state.adding and instance.pk is not None: update_fields = kwargs.get("update_fields", None) old = sender._default_manager.filter(pk=instance.pk).first() _create_log_entry( diff --git a/auditlog_tests/tests.py b/auditlog_tests/tests.py index 5c8ab65..f9bbcb6 100644 --- a/auditlog_tests/tests.py +++ b/auditlog_tests/tests.py @@ -235,6 +235,13 @@ class SimpleModelTest(TestCase): history = self.obj.history.filter(timestamp=timestamp, changes="foo bar") self.assertTrue(history.exists()) + def test_create_duplicate_with_pk_none(self): + initial_entries_count = LogEntry.objects.count() + obj = self.obj + obj.pk = None + obj.save() + self.assertEqual(LogEntry.objects.count(), initial_entries_count + 1) + class NoActorMixin: def check_create_log_entry(self, obj, log_entry): @@ -347,6 +354,9 @@ class ModelPrimaryKeyModelBase(SimpleModelTest): self.key = super().make_object() return ModelPrimaryKeyModel.objects.create(key=self.key, text="I am strange.") + def test_create_duplicate_with_pk_none(self): + pass + class ModelPrimaryKeyModelTest(NoActorMixin, ModelPrimaryKeyModelBase): pass