如何将 Django 中的权限添加到模型并使用 shell 进行测试 [英] how to add Permissions in Django to Models and Test it using the shell

查看:31
本文介绍了如何将 Django 中的权限添加到模型并使用 shell 进行测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模型中添加了 Meta 类并同步了数据库,然后在 shell 中创建了一个对象它返回false,所以我真的不明白错误在哪里,或者缺少什么,是否有某种配置可能在其他一些文件中..

I added the Meta class in my model and synchronized the DB then created an object in the shell it returns false so i really cant understand where is the error or what is missing is there some sort of configuration maybe in some other files ..

class Employer(User): # Employer inherits from User
    employer_verified = models.BooleanField(default=False)

    class Meta:
        permissions = (
            ("is_member", "Friendly permission description"),
        )

emp = Employer.objects.create(blablabla)
emp.save()
emp.has_perm('myappname.is_member')

推荐答案

在你给出的例子中,我希望 emp.has_perm('myappname.is_member') 确实是 False.除非你明确地赋予新的 Employer 对象 is_member 权限,否则它不会拥有它.

In the example you gave, I would expect emp.has_perm('myappname.is_member') to indeed be False. Unless you explicitly give the new Employer object the is_member permission, it won't have it.

要以编程方式授予它您需要获取实际权限对象并将其添加到 Employeruser_permissions 所需的权限:

To programmatically give it the permission you need to get the actual permission object and add it to the Employer's user_permissions:

from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(Employer)
permission = Permission.objects.get(content_type=content_type, codename='is_member')

emp = Employer.objects.create(blablabla)
emp.save()
emp.user_permissions.add(permission)

要在 shell 中测试它,您可能需要删除为每个用户创建的权限缓存 - 否则 has_perm 可能无法反映实际权限:

To test it in the shell, you may need to delete the permission cache that is created for each user- otherwise has_perm may not reflect the actual permissions:

delattr(emp, '_perm_cache')

回答您的问题:

如果您希望每个 Employer 都拥有 is_member 权限,有几个选项:

If you want every single Employer to have the is_member permission there are a few options:

  1. 重写Employersave方法,检查是否没有self.pk(表示是新对象,并在保存后创建我上面显示的权限.不是很漂亮,但它会工作.

  1. Override the save method of Employer to check if there is no self.pk (which means it is a new object, and create the permission as I showed above after saving. Not very pretty, but it would work.

编写自己的身份验证后端.如果权限码是'is_member',并且User有一个Employer实例,返回True

Write your own authentication backend. If the permission code is 'is_member' and the User has an Employer instance, return True

不要使用权限.权限系统旨在让您能够动态授予和撤销权限.如果您只关心 User 是否是 Employer,那么请对其进行测试.不要使用权限使其复杂化.

Don't use permissions. The permission system is designed for you to be able to dynamically grant and revoke permissions. If you only care whether a User is an Employer- then test for that. Don't complicate it by using permissions.

这篇关于如何将 Django 中的权限添加到模型并使用 shell 进行测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆