1

I'm running into a problem where I've created a Group with certain permissions, and successfully added a user to that group, but when I check user.has_perm with that permission, I'm getting False.

I've even tried things like saving the user and re-fetching them from the database to avoid caching issues, but it makes no difference.

The terminal output below should give an idea of what's happening

# Get a group from the database and check its permissions
> special_group = Group.objects.get(name="special_group")
> a_perm = special_group.permissions.all()[0]
> a_perm.codename
'some.permission'

# Get a user from that group and check if they have those permissions
> a_user = special_group.user_set.all()[0]
> a_user.has_perm(a_perm.codename)
False
> a_perm.codename in a_user.get_group_permissions()
False

# Curiously, get_group_permission sort of returns what we need
> a_user.get_group_permissions()
{'ContentType object.some.permission'}

# If we essentially coax the group_permissions into a list and pull an item out of there, has_perm returns true, but this string is different to a_perm.codename
> a_user.has_perm(list(a_user.get_group_permissions())[0])
True

Does anyone know why has_perm isn't behaving as I'm expecting? We are using Django 1.10.3.

warchinal
  • 229
  • 2
  • 14
  • Are you sure user is active? – Adam Dobrawy May 15 '17 at 22:55
  • When you have permission assignment around groups, looks like the cache could be your enemy. Try creating a unit test with your scenario and you will see that it will pass. See more here https://github.com/django-guardian/django-guardian/issues/455 – mugume david Jul 25 '18 at 17:10
  • @mugumedavid thanks you are right! As it says in those docs, `from django.shortcuts import get_object_or_404` , a = get_object_or_404(User, pk=18) refreshed something from the db, cleared a cache and it worked. – cardamom Nov 22 '18 at 14:44

0 Answers0