我可以通过编程方式为群组授予整个应用程序的所有权限吗?
当然,我可以给组中应用程序中每个特定模型的所有添加,更改,删除权限。但是稍后,如果需要添加其他模型,则需要更改代码,并在其中授予权限。
因此,我需要找到一种可能性,即在不知道其名称的情况下,也可以向应用程序内的所有模型授予所有权限。
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)