在Django中添加模型级别权限的步骤

问题描述 投票:0回答:1

我有我的遗留数据库。我使用inspectdb创建了模型。我可以在管理页面中看到我的表格。我创建了 4 个用户,我想为每个模型实现基于角色的权限。我只是用示例向您展示我在模型中添加编辑、查看、删除等权限的操作。 示例:-

class BusinessIntegrationSourceCategory(models.Model):
    date_added = models.DateTimeField(blank=True, null=True)
    date_modified = models.DateTimeField(blank=True, null=True)
    source_category = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'business_integration_source_category'
        permissions = (
            ("view_category", "view category"),
             ("add_category", "Add category"),
            ("delete_category", "Delete category"),
        )

现在我可以添加后续步骤来添加基于角色的权限。

django django-models django-forms
1个回答
1
投票

来自 Django 文档。

处理对象权限

Django的权限框架有对象权限的基础, 尽管核心中没有实现它。这意味着 检查对象权限将始终返回 False 或空 列表(取决于执行的检查)。身份验证后端 将接收每个对象的关键字参数 obj 和 user_obj 相关授权方法并可返回对象级别 酌情获得许可。

如上所述:身份验证后端将接收关键字参数

obj
user_obj

这两个变量是对象级别权限的种子,但默认后端

django.contrib.auth.backends.ModelBackend
并没有利用这一点。所以你应该创建一个自定义后端。

注:

如果您使用自定义

User
模型,您的用户模型应该子类
PermissionsMixin
,因为
PermissionsMixin
的 has_perm 方法将工作传递给注册的身份验证后端。

尝试:

backends.py
文件:

from django.contrib.auth import get_user_model

class MyAuthenticationBackend:

    def authenticate(self, *args, **kwargs):
        pass


    def get_user(self, user_id):
        try:
            return get_user_model().objects.get(pk=user_id)
        except get_user_model().DoesNotExist:
            return None
    
    def has_perm(self, user_obj, perm, obj=None):
        if perm == "view_category":
            return True # everybody can view
        # otherwise only the owner or the superuser can delete
        return user_obj.is_active and obj.user.pk==user_obj.pk
    
    def has_perms(self, user_obj, perm_list, obj=None):
        return all(self.has_perm(user_obj, perm, obj) for perm in perm_list)

settings.py
文件中添加:

AUTHENTICATION_BACKENDS = [
    'your_app.backends.MyAuthenticationBackend',
    # Your other auth backends, if you were using the default,
    # then comment out the next line, otherwise specify yours
    # 'django.contrib.auth.backends.ModelBackend'
    ]

注意:每个模型都已经拥有默认权限(添加、更改和删除)

我希望这会推动你前进。

© www.soinside.com 2019 - 2024. All rights reserved.