2

What is going on here ?

> from django.contrib.auth.models import Permission
> from django.contrib.contenttypes.models import ContentType
> p = Permission.objects.filter(
    content_type = ContentType.objects.get_for_model(Transaction)
).get(
    codename = 'add_transaction'
)
> user.user_permissions.add(p)

> user.user_permissions.all()
[<Permission: myapp | Transaction | Can add Transaction>]
> user.get_all_permissions()
set([])
> user.has_perm('add_transaction')
False
> user.has_perm('myapp.add_transaction')
False

am i missing a save here somewhere ?

3 Answers 3

5

The ModelBackend caches the permissions on the user object. The Django docs suggest that you reload the user from the db after changing the permissions.

user.user_permissions.add(p)
user = User.objects.get(pk=user.pk)
4
  • I hope we can use user.refresh_from_db() now. Sep 29, 2018 at 6:04
  • 2
    No, refresh_from_db will not clear the cache. It is mentioned in the comment in the docs
    – Alasdair
    Sep 29, 2018 at 8:39
  • Added extra model permission not getting reflected on the test db. I managed to update the original db by python manage.py update permission but It shouldn't get reflected while I'm testing.. Does this answer will help in that situation? Sep 29, 2018 at 8:48
  • No, that doesn't sound related to this question/answer.
    – Alasdair
    Sep 29, 2018 at 10:32
0

dgel's answer is correct but incomplete. Both _perm_cache and _user_perm_cache need to be cleared to force a full reload.

for attr in ('_perm_cache', '_user_perm_cache'):
    delattr(user, attr)
-1

I believe user instances have a permissions cache that is populated when it is first pulled from the DB. Try deleting the cache before calling has_perm:

delattr(user, '_perm_cache')

After that, has_perm should work as expected. Normally this isn't an issue as you rarely add then immediately test for permissions on the same user instance (without pulling it from the DB again). Definitely can trip you up when you're testing in the python shell though.

1
  • Wonder why django doesn't have a built in way of purging an object cache. This is a pretty commno use case (add the permission and perform the action ... ).
    – haki
    Jan 14, 2015 at 7:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.