是否可以在连接到 pre_delete 信号的回调中获得登录的 django 用户(调用模型的删除方法)?
问问题
2383 次
1 回答
6
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)
于 2012-07-16T08:55:52.730 回答