gpt4 book ai didi

django - django 中 pre_delete 信号中的当前用户

转载 作者:行者123 更新时间:2023-12-01 23:54:40 24 4
gpt4 key购买 nike

是否可以在连接到 pre_delete 信号的回调中获取登录的 django 用户(调用模型的删除方法)?

最佳答案

pre_delete 信号不会传递请求实例,但您可以添加一个装饰器来添加它,并在 View 上使用该装饰器,这会删除指定的模型。

假设这是回调函数:

def pre_delete_cb(sender, instance, using, **kwargs):
pass

正在装饰器中添加:

from django.db.models.signals import pre_delete
from functools import wraps
from django.utils.decorators import available_attrs

def pre_delete_dec(cb, sender):
def decorator(view_func):
@wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
cb.request = request # here we add the request to the callback function
pre_delete.connect(cb, sender=sender) # and connecting the real pre_delete to the callback
return view_func(request, *args, **kwargs)
return _wrapped_view
return decorator

并以您调用的方式在 View 上使用装饰器 - 而不是 pre_delete.connect(pre_delete_cb, MyModel),使用:

@pre_delete_dec(pre_delete_cb, MyModel)
def myview(request):

然后在回调中您可以通过以下方式访问请求:

def pre_delete_cb(sender, instance, using, **kwargs):
current_user = pre_delete_cb.request.user

您可以在全局级别添加此内容,而不仅仅是每个 View - 使用中间件:

from django.db.models.signals import pre_delete

def pre_delete_cb(sender, instance, using, **kwargs):
current_user = pre_delete_cb.request.user

class PreDeleteMiddleware(object):
def process_view(self, request, view_func, view_args, view_kwargs):
pre_delete_cb.request = request
from myapp.models import MyModel
pre_delete.connect(pre_delete_cb, sender=MyModel)

关于django - django 中 pre_delete 信号中的当前用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11499953/

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