在 post_save 信号中访问用户的请求
我在我的项目中完成了以下 post_save 信号。
from django.db.models.signals import post_save
from django.contrib.auth.models import User
# CORE - SIGNALS
# Core Signals will operate based on post
def after_save_handler_attr_audit_obj(sender, **kwargs):
print User.get_profile()
if hasattr(kwargs['instance'], 'audit_obj'):
if kwargs['created']:
kwargs['instance'].audit_obj.create(operation="INSERT", operation_by=**USER.ID**).save()
else:
kwargs['instance'].audit_obj.create(operation="UPDATE").save()
# Connect the handler with the post save signal - Django 1.2
post_save.connect(after_save_handler_attr_audit_obj, dispatch_uid="core.models.audit.new")
operation_by 列,我想获取 user_id 并存储它。知道如何做到这一点吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
做不到。当前用户只能通过请求获得,这在使用纯模型功能时不可用。以某种方式访问视图中的用户。
Can't be done. The current user is only available via the request, which is not available when using purely model functionality. Access the user in the view somehow.
您可以借助中间件来做到这一点。在您的应用中创建
get_request.py
。然后将此中间件添加到您的设置中:
然后将导入添加到您的信号中:
You can do that with the help of middleware. Create
get_request.py
in your app. ThenThen add this middleware to your settings:
Then add import to your signals:
我可以通过检查堆栈并查找视图,然后查看视图的局部变量来获取请求。感觉有点像黑客,但它确实有效。
I was able to do it by inspecting the stack and looking for the view then looking at the local variables for the view to get the request. It feels like a bit of a hack, but it worked.
伊格纳西奥是对的。 Django 的模型信号旨在通知其他系统组件有关与实例及其相关数据相关的事件,因此我认为您不能从模型
post_save
信号访问请求数据是有效的,除非该请求数据存储在实例上或与实例关联。我想有很多方法可以处理它,从更坏到更好,但我想说这是创建基于类/基于函数的通用视图的一个主要示例,该视图将自动处理这个问题为你。
让继承自
CreateView
、UpdateView
或DeleteView
的视图另外继承自AuditMixin
类(如果它们处理以下动词)对需要审核的模型进行操作。然后,AuditMixin 可以挂钩到成功创建\更新\删除对象并在数据库中创建条目的视图。非常有意义,非常干净,易于插拔,并孕育出快乐的小马。反面?您要么必须使用即将发布的 Django 1.3 版本,要么必须花一些时间调整基于函数的通用视图并为每个审核操作提供新的视图。
Ignacio is right. Django's model signals are intended to notify other system components about events associated with instances and their respected data, so I guess it's valid that you cannot, say, access request data from a model
post_save
signal, unless that request data was stored on or associated with the instance.I guess there are lots of ways to handle it, ranging from worse to better, but I'd say this is a prime example for creating class-based/function-based generic views that will automatically handle this for you.
Have your views that inherit from
CreateView
,UpdateView
orDeleteView
additionally inherit from yourAuditMixin
class if they handle verbs that operate on models that need to be audited. TheAuditMixin
can then hook into the views that successfully create\update\delete objects and create an entry in the database.Makes perfect sense, very clean, easily pluggable and gives birth to happy ponies. Flipside? You'll either have to be on the soon-to-be-released Django 1.3 release or you'll have to spend some time fiddlebending the function-based generic views and providing new ones for each auditing operation.
为什么不添加一个中间件,如下所示:
然后在您的代码中(特别是在该主题中的信号中):
Why not adding a middleware with something like this :
and later in your code (specially in a signal in that topic) :
为了可追溯性,向您的模型添加两个属性(
created_by
和updated_by
),在“updated_by”中保存最后修改记录的用户。然后在您的信号中您有用户:models.py:
views.py
Signals.py
For traceability add two attributes to your Model(
created_by
andupdated_by
), in "updated_by" save the last user who modified the record. Then in your signal you have the user:models.py:
views.py
signals.py
您也可以使用 django-reversion 来实现此目的,例如,
阅读有关其 API 的更多信息 https://django-reversion.readthedocs.io/en/stable/api.html#revision-api
You could also use django-reversion for this purpose, e.g.
Read more on their API https://django-reversion.readthedocs.io/en/stable/api.html#revision-api
您可以通过重写模型
save()
方法并将保存的实例上的用户设置为附加参数来进行小修改。为了获取用户,我使用了django_currentuser.middleware.ThreadLocalUserMiddleware
中的get_current_authenticated_user()
(参见 https://pypi.org/project/django-currentuser/)。在您的
models.py
中:在您的
signals.py
中:PS:不要忘记将
'django_currentuser.middleware.ThreadLocalUserMiddleware'
添加到您的MIDDLEWARE_CLASSES
。You can do a small hack by overriding you model
save()
method and setting the user on the saved instance as additional parameter. To get the user I usedget_current_authenticated_user()
fromdjango_currentuser.middleware.ThreadLocalUserMiddleware
(see https://pypi.org/project/django-currentuser/).In your
models.py
:In your
signals.py
:PS: Don't forget to add
'django_currentuser.middleware.ThreadLocalUserMiddleware'
to yourMIDDLEWARE_CLASSES
.我想您应该已经弄清楚了这一点,但我遇到了同样的问题,并且我意识到我创建的所有实例都引用了创建它们的用户(这就是您正在寻找的)
I imagine you would have figured this out, but I had the same problem and I realised that all the instances I create had a reference to the user that creates them (which is what you are looking for)
我猜有可能。
在models.py中
在views.py中
在signals.py中
否?
it's possible i guess.
in models.py
in views.py
in signals.py
No ?
可以通过检查从帧记录中获取请求对象。
Request object can be obtained from frame record by inspecting.