使用自定义User类迁移到django-guardian权限

时间:2018-03-04 22:02:22

标签: django django-guardian

我正在尝试迁移我的模型以使用Guardian权限。此时我有:

class Data(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    class Meta:
        permissions = (
            ('view', 'View'),
            ('edit', 'Edit'),
            ('owner', 'Owner'),
        )

我创建了一个添加新权限的迁移,在自定义迁移中,我尝试分配这样的权限:

def assignDataPermissions(apps, schema_editor):
    Data = apps.get_model('api', 'Data')
    for data in Data.objects.all():
        assign_perm('api.owner', data.user, data)


class Migration(migrations.Migration):
    dependencies = [
        ('api', '0169_auto_20180304_1619'),
    ]

    operations = [
        migrations.RunPython(assignDataPermissions)
    ]

这失败了 guardian.exceptions.NotUserNorGroup: User/AnonymousUser or Group instance is required (got EmailUser object)

有更好/适当的方式迁移到Guardian吗?如果没有,我如何让它看到我的自定义用户类?

2 个答案:

答案 0 :(得分:1)

通常,在迁移中加载外部库很容易出错。

尝试低级别的东西:

def assignDataPermissions(apps, schema_editor):
    Data = apps.get_model('api', 'Data')
    Permission = apps.get_model('auth', 'Permission')
    owner_api = Permission.objects.get(content_type__applabel='api', codename='owner')
    UserObjectPermission = apps.get_model('guardian', 'UserObjectPermission')
    for data in Data.objects.all():
        UserObjectPermission.objects.create(permission=owner_api, user=data.user, content_object=data)

答案 1 :(得分:0)

我最终使用了更高级别的解决方法。 在迁移内,data.user实际上是__fake.EmailUser的对象,而get_user_model()则返回custom_user.models.EmailUser。结果,Guardian未通过支票isinstance(identity, get_user_model())

我的解决方法(黑客?)是显式从数据库中获取EmailUser对应的data.user对象。像这样:

def assignDataPermissions(apps, schema_editor):
    Data = apps.get_model('api', 'Data')
    User = get_user_model()
    for data in Data.objects.all():
        user = User.objects.get(id=data.user_id)
        assign_perm('api.owner', user, data)