From 1023c6c5022f364659082da114df2702b4ea3853 Mon Sep 17 00:00:00 2001 From: Yohann D'ANELLO Date: Sun, 6 Sep 2020 20:18:59 +0200 Subject: [PATCH] Use pre_delete signal insted of Model.delete() to prevent note balance issues when deleting a transaction (don't do it) in Django Admin --- apps/note/apps.py | 7 ++++++- apps/note/models/transactions.py | 8 -------- apps/note/signals.py | 8 ++++++++ 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/apps/note/apps.py b/apps/note/apps.py index 4881e3b9..b3dc5a0f 100644 --- a/apps/note/apps.py +++ b/apps/note/apps.py @@ -3,7 +3,7 @@ from django.apps import AppConfig from django.conf import settings -from django.db.models.signals import post_save +from django.db.models.signals import post_save, pre_delete from django.utils.translation import gettext_lazy as _ from . import signals @@ -25,3 +25,8 @@ class NoteConfig(AppConfig): signals.save_club_note, sender='member.Club', ) + + pre_delete.connect( + signals.delete_transaction, + sender='note.transaction', + ) diff --git a/apps/note/models/transactions.py b/apps/note/models/transactions.py index a4f220bd..d10bf3a6 100644 --- a/apps/note/models/transactions.py +++ b/apps/note/models/transactions.py @@ -242,14 +242,6 @@ class Transaction(PolymorphicModel): self.destination._force_save = True self.destination.save() - def delete(self, **kwargs): - """ - Whenever we want to delete a transaction (caution with this), we ensure the transaction is invalid first. - """ - self.valid = False - self.save(**kwargs) - super().delete(**kwargs) - @property def total(self): return self.amount * self.quantity diff --git a/apps/note/signals.py b/apps/note/signals.py index 06bb480b..51ed92d8 100644 --- a/apps/note/signals.py +++ b/apps/note/signals.py @@ -24,3 +24,11 @@ def save_club_note(instance, raw, **_kwargs): from .models import NoteClub NoteClub.objects.get_or_create(club=instance) instance.note.save() + + +def delete_transaction(instance, **_kwargs): + """ + Whenever we want to delete a transaction (caution with this), we ensure the transaction is invalid first. + """ + instance.valid = False + instance.save()