Skip to content

Commit

Permalink
Properly handle the post delete signal in transactions
Browse files Browse the repository at this point in the history
  • Loading branch information
mschoettle committed Sep 14, 2024
1 parent d6d9b19 commit bc0e684
Show file tree
Hide file tree
Showing 2 changed files with 10 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

0 comments on commit bc0e684

Please sign in to comment.