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

Question:

I need to call a function whenever I have an object of a model deleted via admin page. How can I do such thing?

Asked By: ParsaAi

||

Answers:

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).

Answered By: Milo Persic
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.

Answered By: Hamza Riffi

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()
Answered By: Weilory

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
Answered By: Quest
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.