删除用户的权限(django)

kar*_*rna 3 python django permissions django-permissions

我有一个问题,即在视图中甚至在shell中删除用户的权限.让我解释一下我的问题:

我在shell中做了那些测试:

org = Organisateur.objects.get(user__username__contains="ghj") 
content_type = ContentType.objects.get_for_model(Tournoi)
Run Code Online (Sandbox Code Playgroud)

Tournoi是模型的名称

permission_ecriture = 'ecriture_Palaiseau'
permission = Permission.objects.get(content_type=content_type, codename=permission_ecriture)
org.user.user_permissions.remove(permission)`
Run Code Online (Sandbox Code Playgroud)

但是当我写道:

org.user.has_perm('inscription.ecriture_Palaiseau')` 
Run Code Online (Sandbox Code Playgroud)

它返回True

但是当我重写时:

org = Organisateur.objects.get(user__username__contains="ghj")
org.user.has_perm('inscription.ecriture_Palaiseau')`
Run Code Online (Sandbox Code Playgroud)

它返回False

这真的很奇怪.它为什么会这样?

在我的观点中,即使我写了,似乎也没有删除权限:

org = Organisateur.objects.get(user__username__contains="ghj")
Run Code Online (Sandbox Code Playgroud)

(删除权限后,用户仍然拥有它)

我想要做的是删除用户的权限,并在之后立即向同一用户添加另一个权限.但每次我这样做,用户仍然有"删除权限"......

非常感谢你

我期待很快收到你们的回复.

Dan*_*per 7

此行为是预期的,因为权限是缓存的.来自Django文档:

权限缓存

ModelBackend在第一次需要获取权限检查后对User对象进行高速缓存的权限.这通常适用于请求 - 响应周期,因为通常不会在添加权限后立即检查权限(例如,在管理员中).如果要添加权限并在之后立即检查它们,例如,在测试或视图中,最简单的解决方案是从数据库中重新获取用户.