Django group permissions for whole app

…衆ロ難τιáo~ 提交于 2019-12-11 03:47:08

问题


Can I give a group all permissions for a whole application programmatically?
Of course I could give the group all add,change,delete permissions for every specific model in the application. But later, if I need to add another model, I need to change the code, where I give the permissions, too.
So I need find a possibility to grant all permissions too all models inside an app, without knowing their names.
The Django documentation doesn't help me with that.

Edit
To give you a bit more details: I sublcassed the RemoteUserBackend and overrode the configure_user method to add a new user to a specific group. If this group isn't created, I create it and want to give it the necessary permissions:

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()

回答1:


This is quick sketch of management command that syncs app models permissions with group:

# 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)



回答2:


You could make the users of the group superusers, then when you check permissions, do:

if user.is_superuser:
    #allow
else:
    #check permissions


来源:https://stackoverflow.com/questions/21039558/django-group-permissions-for-whole-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!