Django Check and set permissions for a user group
I have a usergroup called baseusers with a set of permissions I have added via admin. If baseusers doesn't exist I want to create it and set the same permissions it has now. I can create the group but how do I find out the permissions from shell and then add them in my code? For example two of the permissions are named can_fm_list and can_fm_add. Application is called fileman. But do I need to use id:s instead? Here is the code I would like the permissions to be set.
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()
Take a look at this blog post: Django: Using The Permission System
Adapted to your example:
can_fm_list = Permission.objects.get(name='can_fm_list')
newgroup.permissions.add(can_fm_list)
For others who are looking for adding multiple permissions at once,
permissions_list = Permission.objects.all()
new_group.permissions.set(permissions_list)
list of permissions add to a new group :-
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)
精彩评论