5

I have an issue with removing permissions to users in view or even in the shell. Let me explain my problem:

I did those tests in the shell:

org = Organisateur.objects.get(user__username__contains="ghj") 
content_type = ContentType.objects.get_for_model(Tournoi)

Tournoi is the name of a model

permission_ecriture = 'ecriture_Palaiseau'
permission = Permission.objects.get(content_type=content_type, codename=permission_ecriture)
org.user.user_permissions.remove(permission)`

but when I write:

org.user.has_perm('inscription.ecriture_Palaiseau')` 

it returns True

but when I rewrite:

org = Organisateur.objects.get(user__username__contains="ghj")
org.user.has_perm('inscription.ecriture_Palaiseau')`

it returns False

It is really weird. Why does it works like this?

In my views, it seems that the permissions are not removed even if I do write:

org = Organisateur.objects.get(user__username__contains="ghj")

(after removing the permission, the user still has it)

What I want to do is to remove a permission from an user and add another permission to the same user immediately after. But each time I do that, the user still has the "removed permission"......

Thank you very much

I look forward to hearing from you all soon.

M.javid
  • 6,387
  • 3
  • 41
  • 56
karna
  • 61
  • 2
  • 4

2 Answers2

9

This behavior is expected because permissions are cached. From the Django docs:

Permission caching

The ModelBackend caches permissions on the User object after the first time they need to be fetched for a permissions check. This is typically fine for the request-response cycle since permissions are not typically checked immediately after they are added (in the admin, for example). If you are adding permissions and checking them immediately afterward, in a test or view for example, the easiest solution is to re-fetch the User from the database.

Community
  • 1
  • 1
Daniel Hepper
  • 28,981
  • 10
  • 72
  • 75
0

Your code is almost right, you just have forgotten to save your user object at the end!

use user.save()

mjavadtatari
  • 51
  • 2
  • 9