首页 > 解决方案 > Django user.has_perm 返回 false

问题描述

当 user.has_perm 总是返回 true 时,我遇到了一些奇怪的问题,即使表中肯定有权限。也许以前有人这样?接缝仅在最新版本中出现

测试显示问题如下:

import django
import datetime
django.setup()


from django.contrib.auth.models import User

u=User.objects.get(pk=177)

print("version %s" % str(django.VERSION))
print("1: %s" %str(u.has_perm('not_show_tos')))


from django.contrib.auth.models import Permission
permissions = Permission.objects.filter(user=u)

sorted_list_of_permissions = sorted(list(permissions))
print("2:%s " % str("not_show_tos" in sorted_list_of_permissions));
for i in sorted_list_of_permissions:
  print( str(i.codename))
  print("%s" %str(u.has_perm(i.codename)))
  print("\n")

p=Permission.objects.get(codename='not_show_tos');
print("4 %s " % str(p))
print("5 %s " % str(p in sorted_list_of_permissions))
print("6 %s " % str(u.has_perm(p)))

测试结果

 python3 /tmp/test.py 
signals init done.
version (2, 0, 6, 'final', 0)
1: False
2:False 
not_show_tos
False


4 sessions | session | Not Show Tos Page 
5 True 
6 False 

标签: pythondjango

解决方案


您传递给 has_perm 的字符串应该是 format "<app_label>.<permission.codename>"。那是:u.has_perm('sessions.not_show_tos')

来自 django 文档:

has_perm(perm, obj=None)

如果用户具有指定的权限,则返回 True,其中 perm 的格式为"<app_label>.<permission.codename>"。(请参阅有关权限的文档)。如果用户处于非活动状态,此方法将始终返回 False。

如果传入 obj,则此方法不会检查模型的权限,而是检查此特定对象。

https://docs.djangoproject.com/en/2.2/ref/contrib/auth/#django.contrib.auth.models.User.has_perm


推荐阅读