动态检查权限

时间:2012-05-01 06:14:26

标签: python django permissions authentication

class Task(models.Model):

    class Meta:
        permissions = (
            ("view_task", "Can see available tasks"),
            ("change_task_status", "Can change the status of tasks"),
            ("close_task", "Can remove a task by setting its status as closed"),
        )
user.has_perm('app.view_task')

有没有办法检查权限,如果我有contenttype.codename未知(非硬编码),即它来自数据库动态如下

permission = Permission.objects.get(id=item.permission_id )
contenttype = ContentType.objects.get(id=permission.content_type_id)               
user.has_perm(appname.contenttype.codename)

但它总是返回false

1 个答案:

答案 0 :(得分:0)

尝试

user.has_perm(u'%s.%s' % (contenttype.app_label, permission.codename))

另外,使用

contenttype = ContentType.objects.get_for_model(Permission)