How to get user permissions?


Question

I want to retrieve all permission for user as list of premission id's but:

user.get_all_permissions()

give me list of permission names. How to do it?

1
24
9/10/2014 5:53:48 AM

Accepted Answer

The key is get the permission objects like this:

from django.contrib.auth.models import Permission
permissions = Permission.objects.filter(user=user)

and there you can access the id property like this:

permissions[0].id

If you want the list (id, permission_name) do the following:

perm_tuple = [(x.id, x.name) for x in Permission.objects.filter(user=user)]

Hope it helps!

17
3/21/2017 3:10:35 PM

to get all the permissions of a given user, also the permissions associated with a group this user is part of:

from django.contrib.auth.models import Permission

def get_user_permissions(user):
    if user.is_superuser:
        return Permission.objects.all()
    return user.user_permissions.all() | Permission.objects.filter(group__user=user)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon