Home > OS >  Django user doesn't inherit its groups permissions
Django user doesn't inherit its groups permissions

Time:07-22

In my Django project my jack user is in a group called 'Personals'. 'Personals' group has a permission named 'personal'. But jack doesn't inherit that permission from its group. Jack user doesn't have the 'personal' permission which its groups have. Why jack user didn't take the permission from its group?

>>>jack = User.objects.get(username="jack")
>>>jack_permissions = Permission.objects.filter(user=jack)
>>>print(jack_permissions)
<QuerySet []>   #It gives a emty query.

>>>jack_group = jack.groups.all()
>>>print(jack_group)
Personals
>>>jacks_group = Group.objects.get(name="Personals")
>>>jacks_groups_permissions = jacks_group.permissions.all()
>>>print(jacks_groups_permissions)
<QuerySet [<Permission: auth | user | The Personals>]>      #The Group has the permission The Personals

CodePudding user response:

Use User.get_all_permissions() to get all permissions that the user has including permissions inherited from groups or use User.get_group_permissions to get all permissions that a user has from their groups

jack_permissions = jack.get_all_permissions()

CodePudding user response:

I presume your many-to-one relation chain is like the following:

User > Group > Permission

And you want to get all permissions related to a particular user. If so, you can use double-underscore (__) notation to get the through relationship.

Does this get you what you want?

jack = User.objects.get(username="jack")
jack_permissions = Permission.objects.filter(group__users=jack)
  • Related