Django user get_all_permissions() is empty while user_permissions is set
Asked Answered
S

2

30

I added some permissions to a user via the admin interface.

From some reason all the perm functions fail, e.g

>>> user.get_all_permissions()
set([])

But accessing the table directly, works:

>>> user.user_permissions.all()
(list of permissions as expected)

What can cause the "get_all_permissions" (and all the perm functions like has_perm()) to fail ?

Thanks

Shrub answered 17/1, 2010 at 13:15 Comment(1)
What's the authentication backends in your settings.py?Quail
C
50

had the same problem. I am guessing that at some point you have used a self-crafted AUTHENTICATION_BACKEND? Most examples on the net of this (INCLUDING THE DJANGO 1.0 DOCUMENTATION!) don't mention that the Backends are responsible for permissions handling as well.

However, no biggie: In whatever backend file your code resides, include this import:

from django.contrib.auth.backends import ModelBackend

Then make sure the Backend you wrote extends ModelBackend, e.g.:

class EmailBackend(ModelBackend):

Should be fine.

Courtyard answered 3/5, 2010 at 13:15 Comment(1)
Yep, I found it out later. I modified the backend to support case-insensitive usernames and broke the permissions.Shrub
F
2

In my case it was because of permission caching. I get the user, added permission to user.user_permissions but user.get_all_permissions was empty set() and user.has_perm was False. This problem is only with shell not admin.

user = User.objects.get(username="User")

permission = Permission.objects.get(
    codename="organizations.add_organization",
)
user.user_permissions.add(permission)

user.get_all_permissions()  # set()
user.has_perm('organizations.add_organization')  # False

I have to add additional line before checking permissions:

user.user_permissions.add(permission)

user = User.objects.get(username="User") # new

user.get_all_permissions()
Firebug answered 12/11, 2021 at 17:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.