Skip to content

Commit

Permalink
Properly handle the post delete signal in transactions
Browse files Browse the repository at this point in the history
If the model changes are committed in a transaction,
at the time when the post delete signal is handled
instance.pk returns None.

Store the instance's ID beforehand so that it is available
when creating the CRUDEvent.
  • Loading branch information
mschoettle committed Sep 14, 2024
1 parent 94b2c57 commit 3ced73b
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 3 deletions.
10 changes: 7 additions & 3 deletions easyaudit/signals/crud_flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ def get_current_user_details():
return user_id, user_pk_as_string


def log_event(event_type, instance, object_json_repr, **kwargs):
def log_event(event_type, instance, object_id, object_json_repr, **kwargs):
user_id, user_pk_as_string = get_current_user_details()
with transaction.atomic(using=DATABASE_ALIAS):
audit_logger.crud(
{
"content_type_id": ContentType.objects.get_for_model(instance).id,
"datetime": timezone.now(),
"event_type": event_type,
"object_id": instance.pk,
"object_id": object_id,
"object_json_repr": object_json_repr or "",
"object_repr": str(instance),
"user_id": user_id,
Expand All @@ -70,6 +70,7 @@ def pre_save_crud_flow(instance, object_json_repr, changed_fields):
log_event(
CRUDEvent.UPDATE,
instance,
instance.pk,
object_json_repr,
changed_fields=changed_fields,
)
Expand All @@ -82,6 +83,7 @@ def post_save_crud_flow(instance, object_json_repr):
log_event(
CRUDEvent.CREATE,
instance,
instance.pk,
object_json_repr,
)
except Exception:
Expand All @@ -102,18 +104,20 @@ def m2m_changed_crud_flow( # noqa: PLR0913
log_event(
event_type,
instance,
instance.pk,
object_json_repr,
changed_fields=changed_fields,
)
except Exception:
handle_flow_exception(instance, "pre_save")


def post_delete_crud_flow(instance, object_json_repr):
def post_delete_crud_flow(instance, object_id, object_json_repr):
try:
log_event(
CRUDEvent.DELETE,
instance,
object_id,
object_json_repr,
)

Expand Down
3 changes: 3 additions & 0 deletions easyaudit/signals/model_signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,13 @@ def post_delete(sender, instance, using, **kwargs):

with transaction.atomic(using=using):
object_json_repr = serializers.serialize("json", [instance])
# instance.pk returns None if the changes are performed within a transaction
object_id = instance.pk

crud_flow = partial(
post_delete_crud_flow,
instance=instance,
object_id=object_id,
object_json_repr=object_json_repr,
)
if getattr(settings, "TEST", False):
Expand Down
23 changes: 23 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import pytest
from asgiref.sync import sync_to_async
from django.db import transaction
from django.contrib.contenttypes.models import ContentType
from django.core import management
from django.urls import reverse
Expand Down Expand Up @@ -189,6 +190,28 @@ def test_delete(self, model):
)
assert crud_event_qs.count() == 2

@pytest.mark.django_db(transaction=True)
def test_delete_transaction(self, model, settings):
settings.TEST = False

with transaction.atomic():
obj = model.objects.create()
model.objects.all().delete()

crud_event_qs = CRUDEvent.objects.filter(
object_id=obj.id,
content_type=ContentType.objects.get_for_model(obj),
event_type=CRUDEvent.CREATE,
)
assert crud_event_qs.count() == 1

crud_event_qs = CRUDEvent.objects.filter(
object_id=obj.id,
content_type=ContentType.objects.get_for_model(obj),
event_type=CRUDEvent.DELETE,
)
assert crud_event_qs.count() == 1

@pytest.mark.usefixtures("_audit_logger")
def test_propagate_exceptions(self, model, settings):
with pytest.raises(ValueError, match="Test exception"):
Expand Down

0 comments on commit 3ced73b

Please sign in to comment.