gpt4 book ai didi

python - Django:使用post_delete信号确定哪个用户正在删除

转载 作者:太空狗 更新时间:2023-10-30 00:00:23 25 4
gpt4 key购买 nike

我希望在删除某些对象时通知管理员,但我还想确定哪个用户正在执行删除操作。

这可能吗?

这是代码:

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

最佳答案

我怀疑是否可以使用内置信号(没有 User 隐式绑定(bind)到 delete 操作,并且由于 Django 的 loose coupling 数据库层没有不要处理 HttpRequest 对象)。我会创建我自己的信号,它提供一个 user 参数,并在删除操作发生的任何 View 中发送它,比如:

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

关于python - Django:使用post_delete信号确定哪个用户正在删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6847952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com