且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将 Django 中的权限添加到模型并使用 shell 进行测试

更新时间:2023-12-01 13:11:40

在你给出的例子中,我希望 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.