2012-01-04 69 views
2

如何在django中調試權限問題?調試Django權限錯字

我用這樣的代碼:

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

我怎麼能知道是否有在「foo.bar」一個錯字?

回答

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) 
+0

你可以寫你自己的後端做到這一點,而不是修改的Django源:https://docs.djangoproject.com/en/1.3/topics/auth/#handling-authorization-in-custom-backends – 2012-01-04 18:42:17

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 
+0

另一種解決方案(暫時修改django的源)或定製的後端有一個優點:我可以運行我所有的單元測試,並查看是否有任何錯字。 – guettli 2012-01-05 10:43:00

+1

你問過關於調試的問題,而不是單元測試。儘管如此,仍然有用。我絕對推薦在猴子補丁上定製後端。這樣你也可以確保你只啓用它進行測試,而不是生產 – second 2012-01-05 10:50:55