2

I'm working on a Django/Wagtail project. I'm trying to build a very customized feature that requires an object to be deleted when hitting the Save button when certain conditions are met.

I override the Save method:

def save(self, *args, **kwargs):

    if condition:
        return super(ArticleTag, self).delete()

    else:
        return super(ArticleTag, self).save(*args, **kwargs)

I know this looks very odd and completely anti-adviseable, but it is exactly the behavior I'm trying to achieve.

Is there a better or "correct" way to do this?

Are there other steps to exactly reproduce the behavior as if the user had hit Delete directly?

Pablo Viacheslav
  • 873
  • 1
  • 8
  • 15

2 Answers2

4

If the object already exists in your db, you can do as follows:

def save(self, *args, **kwargs):

    if condition:
        self.delete() # you do not need neither to return the deleted object nor to call the super method. 
    else:
        return super(ArticleTag, self).save(*args, **kwargs)
floatingpurr
  • 7,749
  • 9
  • 46
  • 106
  • This worked! But I'm facing a new issue, would you check this question? ==> https://stackoverflow.com/questions/49824630/redirect-to-delete-view-in-django-admin – Pablo Viacheslav Apr 13 '18 at 20:25
0

Using signals receivers

signals.py

from django.dispatch import receiver
from django.db.models.signals import post_save

__all__ = ['check_delete_condition']

@receiver(post_save, sender="yourapp.yourmodel")
def check_delete_condition(instance, raw, created, using, updatefields, **kwargs):
    if condition:
        instance.delete()

in your apps.py you can't put the signals import

from .signals import *

#rest of code
Gytree
  • 542
  • 3
  • 13