Django: determine which user deletes when using the post_delete signal

I want administrators to be notified when some objects are deleted, but I also want to determine which user is performing the deletion.

Is it possible?

This is the code:

# models.py # signal to notify admins when nodes are deleted from django.db.models.signals import post_delete from settings import DEBUG def notify_on_delete(sender, instance, using, **kwargs): ''' Notify admins when nodes are deleted. Only for production use ''' if DEBUG: #return False pass # prepare context context = { 'node': instance, 'site': SITE } # notify admins that want to receive notifications notify_admins(instance, 'email_notifications/node-deleted-admin_subject.txt', 'email_notifications/node-deleted-admin_body.txt', context, skip=False) post_delete.connect(notify_on_delete, sender=Node) 
+5
python django django-models django-signals django-sessions
source share
1 answer

I doubt that this is possible using the built-in signals (there is no User implicitly associated with the delete operation, and due to Django the free coupling database level is not connected to HttpRequest ). I would create my own signal that provides a User argument and sends it to any kind of delete operation, for example:

 # myapp/signals.py from django.dispatch import Signal my_post_delete = Signal(providing_args=['instance', 'user']) # myapp/models.py from myapp.signals import my_post_delete ... my_post_delete.connect(notify_on_delete, sender=Node) # myapp/views.py from myapp.signals import my_post_delete ... @login_required def my_delete_view(request, ...) ... instance = Node.objects.get(...) instance.delete() my_post_delete.send(sender=Node, instance=instance, user=request.user) 
+5
source share

All Articles