Django 4.0.1
I when through the Django documentation in order to learn how groups and permissions are
used in Django.
I have set up an AbastractUser with a custom manager:
class User(AbstractUser):
...
objects = UserManager()
...
The manager:
INITIAL_REGISTRATION_GROUP = 'non_subscriber'
class UserManager(BaseUserManager):
def create_user(....)
....
user.save(using=self._db)
non_subscriber_group = Group.objects.get(name=INITIAL_REGISTRATION_GROUP)
user.groups.add(non_subscriber_group)
return user
Now, I have a script that creates groups and permissions:
groups = [
'subscriber',
'free_trial',
'non_subscriber'
]
groups_permissions_mapping = {
'subscriber': 'subscriber_permissions',
'free_trial': 'free_trial_permissions',
'non_subscriber': 'non_subscriber_permissions'
}
class Command(BaseCommand):
help ='Setup user groups and permissions'
@transaction.atomic
def handle(self, *args, **options):
for group in groups:
new_group, created = Group.objects.get_or_create(name=group)
ct = ContentType.objects.get_for_model(User)
permission = Permission.objects.create(
codename=groups_permissions_mapping[group],
name=groups_permissions_mapping[group].replace("_", " ").title(),
content_type=ct
)
new_group.permissions.add(permission)
The problem is that the user instance that is created (or any other existing user that I have added to the non_subscriber
group) doesnât inherit the group permission non_subscriber_permissions
.
On filtering the permission model with a given user it returns an empty queryset
Permission.objects.filter(user=user)
<QuerySet []>
user.get_user_permissions()
set()
But I can see that the userâs group has the missing permission:
user.groups.first().permissions.all()
<QuerySet [<Permission: users | user | Non Subscriber Permissions>]>```
Any idea why permissions are not inherited from the group that the user is assigned on user creation?