我一直在谷歌上搜索数小时试图解决这个问题。没运气。我正在寻找一种方法来获取信号,当一个组添加到用户并且这有效:In Django, how do I get a signal for when a Group has a User added or removed?
当我按照上述问题的指示执行此操作时:
@receiver(m2m_changed)
def my_receiver(*args, **kwargs):
import pprint
pprint.pprint(kwargs)
print kwargs.get('sender').__class__.__name__
if kwargs.get('action') == 'post_add' and isinstance(kwargs.get('instance'), User) :#and isinstance(kwargs.get('model'), Group):
print "here"
...
我得到以下输出:
{'action': u'pre_add',
'instance': <User: GzkDg2j>,
'model': <class 'django.contrib.auth.models.Group'>,
'pk_set': set([1]),
'reverse': False,
'sender': <class 'django.contrib.auth.models.User_groups'>,
'signal': <django.db.models.signals.ModelSignal object at 0x1010d5fd0>,
'using': 'default'}
{'action': u'post_add',
'instance': <User: GzkDg2j>,
'model': <class 'django.contrib.auth.models.Group'>,
'pk_set': set([1]),
'reverse': False,
'sender': <class 'django.contrib.auth.models.User_groups'>,
'signal': <django.db.models.signals.ModelSignal object at 0x1010d5fd0>,
'using': 'default'}
这正是我想要的,但是当我尝试isinstance(kwargs.get('model'),Group)时,所有的地狱都会崩溃。该模型不是Group的实例,它是ModelBase的一个实例。说什么?!您可以通过打印以下内容来查看此内容
print kwargs.get('model').__class__.__name__
发件人同样如此。
所以我需要检查模型或发件人的实例,并确保它们是Group或User_groups。
答案 0 :(得分:1)
我遇到了类似的问题,尝试为组成员身份更改创建接收函数。我最终检查了发件人的内容类型,以确定发件人是User_groups,如下所示:
if ContentType.objects.get_for_model(sender).name == 'user-group relationship':
完整的解决方案如下所示:
@receiver(m2m_changed)
def my_receiver(sender, **kwargs):
# Check if the change is user-group related
if ContentType.objects.get_for_model(sender).name == 'user-group relationship':
if kwargs.get('action') == 'post_add':
# User was added to group(s)
# Do something ...
elif kwargs.get('action') == 'post_remove':
# User was removed from group(s)
# Do something ...