Django检查并设置用户组的权限

emeijp43  于 2022-12-14  发布在  Go
关注(0)|答案(3)|浏览(153)

我有一个名为baseusers用户组,我通过管理员添加了一组权限。如果baseusers不存在,我想创建它并设置与它现在相同的权限。我可以创建该组,但如何从shell中找到权限,然后将它们添加到代码中?例如,其中两个权限名为can_fm_listcan_fm_add。应用程序名为fileman。但是我需要使用id:s来代替吗?下面是我想设置权限的代码。
第一个月

from fileman.models import Setting (Has the permissions)
from fileman.models import Newuserpath
from django.contrib.auth.models import Group

def register(request):

...

            if Group.objects.count() > 0:
            newuser.groups.add(1)
            else:
            newgroup = Group(name='baseusers')
            newgroup.save()
            newuser.groups.add(1)

fileman/models.py

class Setting(models.Model):
    owner = AutoForeignKey(User, unique=True, related_name='fileman_Setting')
    root = models.CharField(max_length=250, null=True)
    home = models.CharField(max_length=250, null=True)
    buffer = models.TextField(blank=True)
    class Meta:
        permissions = (
            ("can_fm_list", _("Can look files list")),
            ("can_fm_add", _("Can upload files")),
            ("can_fm_rename", _("Can rename files")),
            ("can_fm_del", _("Can move files to basket")),
            ("can_fm_destruct", _("Can delete files")),
        )
    def __unicode__(self):
        return unicode(self.owner)
    def __init__(self, *args, **kwargs):
        super(Setting, self).__init__(*args, **kwargs)
        if not self.root:
            self.root = None
            self.home = None
    def writeBuffer(self, data):
        self.buffer = data
        self.save()
yi0zb3m4

yi0zb3m41#

看看这篇博文:Django: Using The Permission System
根据您的示例进行调整:

can_fm_list = Permission.objects.get(name='can_fm_list')
newgroup.permissions.add(can_fm_list)
b0zn9rqh

b0zn9rqh2#

对于希望一次添加多个权限的其他用户,

permissions_list = Permission.objects.all()
new_group.permissions.set(permissions_list)
ftf50wuq

ftf50wuq3#

添加到新组的权限列表:-

group_name = request.POST.get('group_name')
permissions_list = request.POST.getlist('permission')
permissions_list_id = []
new_group = Group.objects.create(name=group_name)

for perm in permissions_list:
    p = Permission.objects.get(name=perm)
    permissions_list_id.append(p.id)

new_group.permissions.set(permissions_list_id)

相关问题