更新时间:2023-12-01 13:16:10
在你给出的例子中,我会期望 emp.has_perm('myappname.is_member' code>确实是
False
。除非你明确地给出新的雇主
对象 is_member
权限,否则不会。
以编程方式给予您获取实际权限对象所需的权限,并将其添加到雇主
的 user_permissions
从django.contrib.auth.models导入权限
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
可能不反映实际权限:
delattr(emp,'_perm_cache')
回答您的问题:
如果您想要每个雇主
有 is_member
权限有几个选项:
覆盖保存
方法$ c>雇主以检查是否没有 self.pk
(这意味着它是一个新对象,并在保存后创建权限,如上所示。不太漂亮,但它会奏效。
编写自己的认证后端。如果权限代码是'is_member'
,而用户
有一个雇主
实例,返回 True
不要使用权限。权限系统旨在让您能够动态授予和撤销权限。如果您只关心用户
是否为雇主
- 然后测试。不要使用权限使其复杂化。
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')
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.
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)
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')
Responding to your questions:
If you want every single Employer
to have the is_member
permission there are a few options:
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.
Write your own authentication backend. If the permission code is 'is_member'
and the User
has an Employer
instance, return True
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.