我在Django post_save信号中添加权限时遇到了问题,因为m2m关系无法持久化。在赋值后,它们正确地显示为user_permissions.all()
,但是当我再次保存模型时,查询集变空了。我做错了什么?
如果使用guardian
在对象级别分配权限,我就不会遇到同样的问题。
- 型号. py**
class User(AbstractBaseUser, PermissionsMixin):
username = models.CharField(db_index=True, max_length=255, unique=True, null=True, blank=True)
last_name = models.CharField(max_length=255, null=True, blank=True)
first_name = models.CharField(max_length=255, null=True, blank=True)
email = models.EmailField(db_index=True, unique=True)
def save(self, *args, **kwargs):
return super(User, self).save(*args, **kwargs)
class Manager(User):
...
def save(self, *args, **kwargs):
return super(Manager, self).save(*args, **kwargs)
- 信号. py**
@receiver(post_save, sender=Manager)
def assign_manager_permissions(sender, instance, created, raw, using, **kwargs):
content_type = ContentType.objects.get_for_model(Manager)
print('Current permissions:')
for p in instance.user_permissions.all():
print(p)
for codename in ['view_manager',
'change_manager',
'add_manager',
'delete_manager']:
permission = Permission.objects.get(content_type=content_type, codename=codename)
instance.user_permissions.add(permission)
instance.refresh_from_db()
print('After refresh permissions:')
for p in instance.user_permissions.all():
print(p)
保存模型时,结果始终相同:
django-1 | Current permissions:
django-1 |
django-1 | After refresh permissions:
django-1 | user | manager | Can add manager
django-1 | user | manager | Can change manager
django-1 | user | manager | Can delete manager
django-1 | user | manager | Can view manager
1条答案
按热度按时间mwg9r5ms1#
我通过使用
transaction.commit
找到了我自己问题的答案,正如所建议的here。