django中pre_delete信号的当前用户

时间:2012-07-16 07:37:55

标签: django django-models django-signals

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

1 个答案:

答案 0 :(得分:5)

pre_delete信号未通过请求实例,但您可以添加装饰器,添加它,并在视图上使用该装饰器,删除指定的模型。

假设这是回调函数:

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

并按照您调用它的方式在视图上使用装饰器 - 而不是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

您可以在全局级别添加此功能,而不仅仅是每个视图 - 使用中间件:

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)