[Django]-How to call a function when you delete a model object in django admin page? (or override delete action?)

3๐Ÿ‘

โœ…

Yes, itโ€™s called a post_delete signal. Here is one way of doing it (you can add this to the bottom of your models.py file, or at least after your model:

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

@receiver(post_delete, sender=YourModelName)
def signal_function_name(sender, instance, using, **kwargs):
    your_function(args)

This function will be called AFTER the object is deleted. There are also pre_save, post_save, among other types of signals.

This signal will be called on delete from within the admin or ANY delete action anywhere (your other logic, views, the python shell, etc).

๐Ÿ‘คMilo Persic

0๐Ÿ‘

create a file signals.py in your app directory, for example, I am trying to remove all relevant tags from author of the article when the article is deleted.

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

from articles.models import Article
from common.methods import tagClear

@receiver(post_delete, sender=Article)
def authorTagClear(sender, instance, using, **kwargs):
    tagClear(instance, instance.author, against=1)

in apps.py define a ready method, this will plugin signals when the app runs.

from django.apps import AppConfig


class ArticlesConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'articles'

    def ready(self):
        import articles.signals
        return super().ready()
๐Ÿ‘คWeilory

0๐Ÿ‘

your normal delete function on the model wonโ€™t work, a way around this is using the post delete sgnal create a file signals.py in your app directory

#signals.py
from django.db.models.signals import post_delete
from django.dispatch import receiver

@receiver(post_delete, sender=ModelName)
def deleting_model(sender, instance, **kwargs):
    #your action goes here
    pass

Then define the ready method in your apps.py

#apps.py
from django.apps import AppConfig


class AppNameConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'appname'

    def ready(self):
        import appname.signals
๐Ÿ‘คQuest

-1๐Ÿ‘

def delete(self):
files = WidgetFile.objects.filter(widget=self)
if files:
    for file in files:
        file.delete()
super(Widget, self).delete()

This triggered the necessary delete() method on each of the related objects, thus triggering my custom file deleting code. Itโ€™s more database expensive yes, but when youโ€™re trying to delete files on a hard drive anyway, itโ€™s not such a big expense to hit the db a few extra times.

๐Ÿ‘คHamza Riffi

Leave a comment