4

I read in Django documentation that when I add an User in a group, it will automatically have the permissions granted to that group. So, in my application I created a group called "admin" via admin interface and I gave the permission I needed to it. Now if I create a new User and add it to the group "owners", it doesn't have the permissions of the group.

Then I tried to experiment it in django shell and it ran well The permissions of the group really assigned to the user_permissions


That's my code in django user model
class UserAccount(AbstractUser):

def __str__(self):  # __unicode__ for Python 2
    return str(self.username)

def __unicode__(self):
    return str(self.username)

def save(self, *args, **kwargs):
    super(UserAccount, self).save(*args, **kwargs)
    for group in set(self.groups.all()):
        self.user_permissions = group.permissions.all()

Another Try

class UserAccount(AbstractUser):

def __str__(self):  # __unicode__ for Python 2
    return str(self.username)

def __unicode__(self):
    return str(self.username)

def save(self, *args, **kwargs):
    super(UserAccount, self).save(*args, **kwargs)
    for group in set(self.groups.all()):
        for perm in group.permissions.all():
            self.user_permissions.add(perm)

Both not working when I save the user from the admin panel interface but both working well at the django shell I tried to debug ipdb and the code executed but permissions not assigned

Then I try to add permissions in reverse way from group

from django.contrib.auth.models import Group as BaseGroup
class Group(BaseGroup):
    class Meta:
        proxy = True

    def save(self):
        super(Group, self).save()
        for user in self.user_set.all():
            user.user_permissions = self.permissions.all()

I don't know if what I did is right or not and if it is right why not work properly.

Update:

No need to assign the permissions as the user has the permissions of the group automatically

ekad
  • 14,436
  • 26
  • 44
  • 46
A.Raouf
  • 2,171
  • 1
  • 24
  • 36

1 Answers1

1

This probably won't work, because the user's permissions are also saved from the admin page.

The following happens:

  1. Your User object is saved

  2. You set permissions in its save() method

  3. Then the permissions as set on the page are saved, overwriting whatever you did in save()

The last one also wouldn't work because assigning to user.user_permissions means you overwrite the related manager property, but other than that it doesn't really do anything.

BUT -- you should just be able to give the user a group, manually in the admin interface, and that should cause the user to have all the permissions assigned to the group.

I note that you say you gave the permissions to a group named "admins" and then made the user part of "owners", but I hope that's just a typo.

RemcoGerlich
  • 30,470
  • 6
  • 61
  • 79