在数据迁移中创建自定义权限

时间:2015-07-23 08:29:43

标签: django django-migrations django-permissions

我尝试在迁移中创建自定义权限,但是在运行迁移后,未在权限表中创建权限。有人能指出错误是什么吗? 此外,我不确定我应该使用什么作为ContentType的相关模型,因为该权限用于限制可以查看显示网站上用户摘要的页面的用户。 非常感谢任何帮助,谢谢。

def add_view_aggregated_data_permissions(apps, schema_editor):
    ContentType = apps.get_model('django', 'ContentType')
    Permission = apps.get_model('auth', 'Permission')
    content_type = ContentType.objects.get(app_label='auth', model='user')
    permission = Permission.objects.create(codename='can_view_data',
                                           name='Can view data',
                                           content_type=content_type)

3 个答案:

答案 0 :(得分:2)

我建议您使用标准方式来使用Django documentation中所述的自定义权限。你将完全避免许多问题。

  

要为给定模型对象创建自定义权限,请使用权限模型Meta属性。

此示例模型创建自定义权限:

class MyModel(models.Model):
    ...
    class Meta:
        permissions = (
            ('view_data', "Can see available data"),
        )
  

这样做的唯一方法就是在运行manage.py migrate时创建额外的权限。当用户试图访问应用程序提供的功能时,您的代码负责检查这些权限的值...

然后,您可以在视图中使用permission_required装饰器来检查特定权限:

from django.contrib.auth.decorators import permission_required

@permission_required('myapp.view_data')
def my_view(request):
    ...

答案 1 :(得分:0)

从django 1.8和内置迁移开始,这是非常无痛的。

  1. 您需要做的就是将相关权限添加到相关的权限中 模型
  2. 运行makemigration

    ./ manage.py makemigrations

  3. 运行上一步中创建的迁移

    ./ manage.py migrate

答案 2 :(得分:0)

我想为所有应用模型创建自定义权限(读取)。我做了两个步骤:

  1. 从DjangoModelPermissions创建扩展权限:

    class DjangoModelPermissionsExtended(DjangoModelPermissions):
        """
        """
        perms_map = {
            'GET': ['%(app_label)s.read_%(model_name)s'],
            'OPTIONS': [],
            'HEAD': [],
            'POST': ['%(app_label)s.add_%(model_name)s'],
            'PUT': ['%(app_label)s.change_%(model_name)s'],
            'PATCH': ['%(app_label)s.change_%(model_name)s'],
            'DELETE': ['%(app_label)s.delete_%(model_name)s'],
        }
    
  2. 将其置于每个视图中我想拥有读取权限:

    class ExampleViewSet(viewsets.ModelViewSet):
        permission_classes = (
            DjangoModelPermissionsExtended,
        )
    
  3. 创建django command customread.py:

    from django.core.management.base import BaseCommand, CommandError
    from project.app import models as app_models
    from django.db import models
    from django.contrib.auth.models import Permission
    from django.contrib.contenttypes.models import ContentType
    import inspect
    
    class Command(BaseCommand):
    help = 'Create the read permission to app models'
    
    def handle(self, *args, **options):
        for name, obj in inspect.getmembers(app_models):
            if inspect.isclass(obj) and issubclass(obj, models.Model):
                try:
                    self.add_canread(obj)
                    self.stdout.write(self.style.SUCCESS(
                        'created permission for %s' % obj
                    ))
                except Exception as e:
                    self.stdout.write(self.style.ERROR(
                        'Permission already exists for %s' % obj
                    ))
    
    def add_canread(self, object_class):
        """This a function that can be executed in order to create
        new permissions (read view) to a class in DB.
    
        """
        if inspect.isclass(object_class):
            content_type = ContentType.objects.get_for_model(object_class)
            permission = Permission.objects.create(
                codename='read_{}'.format(object_class._meta.model_name),
                name='Can view {}'.format(object_class.__name__),
                content_type=content_type,
            )
        else:
            msg = "The object is not a class"
            print(msg)
    
  4. 执行迁移后执行:

    python manage.py customread