Django: determine which user is deleting when using post_delete signal

杀马特。学长 韩版系。学妹 提交于 2019-12-06 02:03:49

问题


I want admins to be notified when certain objects are deleted but I also want to determine which user is performing the delete.

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)

回答1:


I doubt it's possible using the built-in signals (there is no User implicitly tied to a delete operation, and because of Django's loose coupling the database layer doesn't deal with HttpRequest objects). I would create my own signal which provides a user argument and send it in whatever view the delete operation takes place, something like:

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


来源:https://stackoverflow.com/questions/6847952/django-determine-which-user-is-deleting-when-using-post-delete-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!