我能否以编程方式为一个组授予整个应用程序的所有权限?
当然,我可以为该组授予应用程序中每个特定模型的所有添加、更改、删除权限。但是后来,如果我需要添加另一个模型,我需要更改代码,我也在这里授予权限。
所以我需要找到一种可能性,在不知道它们的名字的情况下,将所有权限授予应用程序中的所有模型。
Django 文档对此没有帮助。
编辑
为您提供更多详细信息:我子类化了 RemoteUserBackend 并覆盖了 configure_user 方法以将新用户添加到特定组。如果未创建此组,我将创建它并希望为其授予必要的权限:
class MyRemoteUserBackend(RemoteUserBackend):
def configure_user(self, user):
group, created = Group.objects.get_or_create(name="mygroup")
if created:
pass
# Give permissions here
user.groups.add(group)
group.save()
请您参考如下方法:
这是将应用程序模型权限与组同步的管理命令的速写:
# coding=utf-8
from django.core.management.base import BaseCommand, CommandError
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission, Group
class Command(BaseCommand):
args = '<group_name app_label>'
help = ('Syncs permissions of group with given name with permissions
of all models of app with giver app_label ')
def handle(self, *args, **options):
group_name= args[0]
app_label = args[1]
group = Group.objects.get(name=group_name)
cts = ContentType.objects.filter(app_label=app_label)
perms = Permission.objects.filter(content_type__in=cts)
group.permissions.add(*perms)
