python - 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
解决方案
您传递给 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
推荐阅读
- android - android.useAndroidX=false 构建 ionic android 时的覆盖值
- c++ - 如何成功链接 ImageMagic 静态库?
- json - 如何在 Spark 中更新数据框列
- c# - 我的表情
> 函数不是返回变量值,而是 value.(c__DisplayClass12_7).value - python - Pandas 基于多列计算值的最快方法
- ssh - 通过本地 tmux 会话在 ssh 上使用 tmux 命令
- postgresql - pg_stats_activity.datname 在一条记录上为空
- java - HttpURLConnection 方法卡在当前线程中;
- node.js - 在 node.js 内存存储中设置存储密钥的限制?
- javascript - 过滤掉对象中的计算值