【问题标题】:Steps to add model level permission in Django在 Django 中添加模型级别权限的步骤
【发布时间】:2018-07-09 22:56:10
【问题描述】:

我有我的旧数据库。我使用 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】:

    来自 Django 文档。

    Handling object permissions

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

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

    而这两个变量是对象级权限的种子,但默认后端django.contrib.auth.backends.ModelBackend 没有利用这一点。所以你应该创建一个自定义后端。

    注意:

    如果您使用自定义User 模型,your user model should subclass 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'
        ]
    

    注意:每个模型都已经有default permissions(添加、更改和删除)

    我希望这会推动你前进。

    【讨论】:

    • 感谢 Yusef 的回复。但我使用现有的数据库表在管理页面上显示。我从管理页面创建了新用户,我想在几个表上提供删除和更改访问权限,但我可以' t 在侧面用户屏幕的可用用户权限选项卡中查看表名称。正如我们所知,每个模型都已经拥有默认权限(添加、更改和删除),所以我如何在用户部分查看我的表名
    猜你喜欢
    • 1970-01-01
    • 2013-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 2013-05-15
    • 2011-05-03
    • 1970-01-01
    相关资源
    最近更新 更多