如何在django中調試權限問題?調試Django權限錯字
我用這樣的代碼:
if request.user.has_perm('foo.bar'):
我怎麼能知道是否有在「foo.bar」一個錯字?
如何在django中調試權限問題?調試Django權限錯字
我用這樣的代碼:
if request.user.has_perm('foo.bar'):
我怎麼能知道是否有在「foo.bar」一個錯字?
我找到了答案。只需修改(臨時)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)
嗯,我想你可以看看所有定義的權限:
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
你可以寫你自己的後端做到這一點,而不是修改的Django源:https://docs.djangoproject.com/en/1.3/topics/auth/#handling-authorization-in-custom-backends – 2012-01-04 18:42:17