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()
To do this, create custom permissions. The easiest way of doing this is to define it as part of the model. Specify custom permissions by setting the permissions attribute in a Meta class of a model, like so: class Blog(models.
Add Permissions to a Group If you are using AbstractUser in Django, you must add AUTH_USER_MODEL = 'YourAppName. YourClassName' . This way, you are telling Django to use our custom user model instead of the default one. The code below should go in your admin.py file so that you can see your user model.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With