我想在 User 模型上注册一个信号处理程序,如下所示:
def post_save_handler(sender, instance, created, **kwargs):
should_have_profile = instance.has_perm('profile.should_have')
if should_have_profile:
profile, created = Profile.objects.get_or_create(user=instance)
if crated:
profile.save()
else:
old_profile = Profile.objects.filter(user=instance)
if old_profile:
old_profile.delete()
但是,在信号处理程序中,对新权限(通过更改组成员身份在视图代码中添加或删除)的“has_perm”测试没有正确进入。好像还没有应用新组。
我在 contrib.auth.backends.py 中短暂怀疑过_group_perm_cache
,_perm_cache
但我增强了我的信号处理程序以从传入实例中删除这些值,结果是相同的。
我所能推测的是,对当前组的任何更改都不会传递给该用户。m2m_changed
为此, 我还尝试在 User 对象上注册一个侦听器,但这也没有被调用(可能是因为 User.groups 没有实现为 ManyToManyField)。
有什么办法可以正确地做我想要的吗?