我有一个名为 baseusers 的用户组,其中包含我通过管理员添加的一组权限。如果 baseusers 不存在,我想创建它并设置它现在拥有的相同权限。我可以创建组但是如何从shell中找到权限然后将其添加到我的代码中?例如,两个权限名为 can_fm_list 和 can_fm_add 。应用程序称为 fileman 。但我需要使用id:s吗?这是我想要设置权限的代码。
userprofile/views.py
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()
答案 0 :(得分:16)
请看一下这篇博文:Django: Using The Permission System
改编自您的示例:
can_fm_list = Permission.objects.get(name='can_fm_list')
newgroup.permissions.add(can_fm_list)
答案 1 :(得分:0)
对于正在寻求一次添加多个权限的其他人,
permissions_list = Permission.objects.all()
new_group.permissions.set(permissions_list)