Using Pre_delete Signal in django

In my application, I want to keep track of all issues that are being deleted. And so I created a class (table) as such in my models file.

class Deleted(models.Model): question = models.IntegerField(null=True, blank=True)#id of question being deleted user = models.IntegerField(null=True, blank=True)#id of user deleting the question dt = models.DateTimeField(null=True, blank=True)#time question is deleted 

When a user tries to delete a question, this delete function is called:

 def delete_questions(request, user, questions): for q in questions: q.delete() 

My doubt is how can I make a pre_delete django signal to populate the new table that I created.

~ newbie trying hard task ~ Thanks in advance :)

+8
python django django-models django-signals
source share
1 answer

You start by defining the receiver you want to use:

 def log_deleted_question(sender, instance, using, **kwargs): d = Deleted() d.question = instance.id d.dt = datetime.datetime.now() # consider using auto_now=True in your Deleted definition # not sure how you'd get the user via a signal, # since it can happen from a number of places (like the command line) d.save() 

Then define the receiver decoder:

 from django.db.models.signals import pre_delete from django.dispatch import receiver @receiver(pre_delete, sender=Question, dispatch_uid='question_delete_log') 

Add it at all:

 from django.db.models.signals import pre_delete from django.dispatch import receiver @receiver(pre_delete, sender=Question, dispatch_uid='question_delete_signal') def log_deleted_question(sender, instance, using, **kwargs): d = Deleted() d.question = instance.id d.dt = datetime.datetime.now() d.save() 

You can put this function in your models.py file, since you know that it will be loaded and properly connected.

The problem is that you are not asking the user to delete. Because deletion can be called from django api (command line, shell, etc.), which does not have a request associated with it. For this reason, you can avoid using signals if it is absolutely important that you save the user along with the deletion.

+26
source share

All Articles