在Django中,如何在Group添加或删除用户时获取信号? [英] In Django, how do I get a signal for when a Group has a User added or removed?

查看:378
本文介绍了在Django中,如何在Group添加或删除用户时获取信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Django管理员中,我有时会向或从(现有)组添加或删除用户。发生这种情况时,我希望能够运行一个功能。

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.

我已经看过通过m2m_changed的信号,但似乎需要一个通过类 - 我不认为在这种情况下有一个。

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.

推荐答案

django doc


发件人 - 描述ManyToManyField的中间模型类。当定义多对多字段时,会自动创建此类;您可以使用多对多字段中的通过属性来访问它。

sender - The intermediate model class describing the ManyToManyField. This class is automatically created when a many-to-many field is defined; you can access it using the through attribute on the many-to-many field.

订阅m2m_changed如下所示:

When subscribing to m2m_changed like so:

@receiver(m2m_changed)
def my_receiver(**kwargs):
    from pprint import pprint
    pprint(kwargs)

您将收到一堆像这样的信号(缩写):

You will receive a bunch of signals like this (shortened):

{'sender': <class 'django.contrib.auth.models.User_groups'>,
 'action': 'post_add',
 'instance': <User: bouke>,
 'model': <class 'django.contrib.auth.models.Group'>,
 'pk_set': set([1]),
 'reverse': False,
 'signal': <django.dispatch.dispatcher.Signal object at 0x101840210>,
 'using': 'default'}

所以用户 bouke 已添加到 pk_set 组: [1] 。但是我注意到,管理员布局会清除所有组,然后将所选组添加回来。您将收到的信号为 pre_clear post_clear pre_add post_add 。使用这些信号的组合,您可以存储前和后组。对这些列表进行区分,您可以为用户添加删除和添加的组。

So the user bouke has been added to pk_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 are pre_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.

请注意,信号是相反的( pk_set 实例)编辑组而不是用户。

Note that the signals are the other way around (pk_set and instance) when editing a group instead of a user.

这篇关于在Django中,如何在Group添加或删除用户时获取信号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆