在 Django 中,如何在组添加或删除用户时获取信号?
在 Django 管理中,我有时会向(现有)组添加或删除用户。当发生这种情况时,我希望能够运行一个函数。
我只是使用标准的用户和组模型。
我已经考虑过通过 m2m_changed 使用信号来完成此操作,但似乎需要一个 Through 类 - 我认为在这种情况下没有一个。
In the Django admin I sometimes add or delete users to or from (existing) groups. When this happens I'd like to be able to run a function.
I'm just using the standard User and Group models.
I have looked at doing it with signals, through m2m_changed, but it seems to need a Through class - and I don't think there is one in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自 django 文档:
当像这样订阅 m2m_changed 时:
您将收到一堆像这样的信号(缩短):
因此用户
bouke
已被添加到pk_set
组中:[1 ]
。不过,我注意到管理布局会清除所有组,然后将所选组添加回来。您将收到的信号是pre_clear
、post_clear
、pre_add
,post_add
。使用这些信号的组合,您可以存储前组和后组。通过对这些列表进行比较,您可以为用户删除和添加组。请注意,当编辑组而不是用户时,信号是相反的(
pk_set
和instance
)。From the django doc:
When subscribing to m2m_changed like so:
You will receive a bunch of signals like this (shortened):
So the user
bouke
has been added topk_set
groups:[1]
. However I noted that the admin layout clears all groups and then adds the selected groups back in. The signals you will receive arepre_clear
,post_clear
,pre_add
,post_add
. Using a combination of these signals you could store the pre and post groups. Doing a diff over these lists, you have the deleted and added groups for the user.Note that the signals are the other way around (
pk_set
andinstance
) when editing a group instead of a user.您将在 Django 文档中看到< /a> (v1.11) 您所需的发件人应该是属于
ManyToMany
字段的中间through
字段,无论在何处定义。如果您将其注册为发件人,那么您将听到例如用户向自己添加组以及组向自己添加用户的声音。You'll see in the Django documentation (v1.11) that your desired sender should be the intermediate
through
field belonging to theManyToMany
field, wherever that's defined. If you register that as your sender, then you'll be listening to eg Users adding Groups to themselves, as well as Groups adding Users to themselves.您需要使用
m2m_changed
作为接收器来创建信号。根据官方 Django 文档:因此,最简单的实现如下:
在您的情况下,您希望在从组中添加或删除用户时执行某些操作,因此您可以在获取值时利用
action
参数'pre_add'
、'post_add'
、'pre_remove'
和'post_remove'
。您还可以利用pk_set
参数,该参数包含已添加到关系或从关系中删除的主键值。You need to create a signal using
m2m_changed
as a receiver. According to the official Django documentation:So, the simplest implementation is as follows:
In your case, you want to perform something when a user is added or removed from a group, so you can take advantage of the
action
parameter when it takes the values'pre_add'
,'post_add'
,'pre_remove'
, and'post_remove'
. You can also take advantage ofpk_set
parameter which contains primary key values that have been added to or removed from the relation.尝试使用 django-celery 来实现这一点可能会更好,这样您就可以编写自定义任务,并且根据特定条件(例如删除或添加)您可以触发特定任务。
It might be better to try and achieve this with
django-celery
, that way you can write custom tasks, and based on a certain criteria (such as removal or addition) you can fire of a certain task.