How to get user permissions?
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)
we can get user permission from user objects directly into a list like this
perm_list = user_obj.user_permissions.all().values_list('codename', flat=True)
Try this....
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!
If you are using Django 3.0+, user.get_user_permissions()
gives the codename of all the permissions.
More information here: https://docs.djangoproject.com/en/3.0/ref/contrib/auth/#django.contrib.auth.models.User.get_user_permissions