调试Django Permission Typo

时间:2012-01-04 15:24:41

标签: django django-authentication

如何在django中调试权限问题?

我使用这样的代码:

if request.user.has_perm('foo.bar'):

我怎么知道'foo.bar'中是否有拼写错误?

2 个答案:

答案 0 :(得分:2)

我找到了答案。只需修改(临时)backends.py的代码:

--- django/contrib/auth/backends.py (Revision 17045)
+++ django/contrib/auth/backends.py (Arbeitskopie)
@@ -43,6 +43,9 @@
         return user_obj._perm_cache

     def has_perm(self, user_obj, perm):
+        all_perms=[u'%s.%s' % (ct, name) for ct, name in Permission.objects.values_list('content_type__app_label', 'codename')]
+        if not perm in all_perms:
+            raise Exception('Permission %s does not exist. foo permissions: %s' % (perm, [p for p in all_perms if 'foo' in p]))
         if not user_obj.is_active:
             return False
         return perm in self.get_all_permissions(user_obj)

答案 1 :(得分:1)

我想你可以查看所有已定义的权限:

from django.contrib.auth.models import Permission
perms = ['%s.%s' % (p.content_type.app_label, p.codename) 
    for p in Permission.objects.all()]

>>> 'foo.bar' in perms
False