I stumbled upon a weird behaviour: I add a permission to a user object but the permission check fails.
permission = Permission.objects.get_by_natural_key(app_label='myapp', codename='my_codename', model='mymodel')
user.user_permissions.add(permission)
user.has_permission('myapp.my_codename') # this is False!
I found some posts about user permission caching here and here and the solution seems to be to completely reload the object from the database.
# Request new instance of User
user = get_object_or_404(pk=user_id)
# Now note how the permissions have been updated
user.has_perms('myapp.my_codename') # now it's True
This seems really overkill for me and very un-django-like. Is there really no way to either clear the permission cache oder reload the foreign keys like you can do for an object with refresh_from_db()
?
Thanks in advance!
Ronny
del user._perm_cache; del user._user_perm_cache
. Or you can write your own model backend that doesn't cache the perms, but you probably don't want that. IMO I think reloading is more readable/maintainable – Chittagong