django guardian.exceptions.WrongAppError: Cannot determine content type
django框架使用guardian的get_objects_for_group()方法时,传入了group及perms,如下:
创建模型类:
# homepage
# models.py
class Equipment(models.Model):
name = models.CharField(max_length=25, default='')
class Meta:
db_table = 'equipment'
permissions = (
('get_equip', '查看装备'),
('update_equip', '修改装备'),
('delete_equip', '删除装备'),
('add_equip', '添加装备'),
)
调用guardian查询已有权限对应的对象:
# views.py
from django.contrib.auth.models import Group
from homepage.models import Equipment
from guardian.shortcuts import assign_perm, get_objects_for_group
group = Group.objects.get(id=2)
perms = get_objects_for_group(group, 'get_equip') # <<== 该行错误
然后抛出了异常:
guardian.exceptions.WrongAppError: Cannot determine content type
中文翻译意为:
无法确定内容类型
解析: content type在django权限模块里代表的是模型类相关的标识,推测是传入的perms参数格式不对导致没有找到预期的模型类,简单分析并尝试后,发现正确的格式应该是要带上对应模型类所在的app的名字,它才能找到模型类
正确的写法是:
group = Group.objects.get(id=2)
perms = get_objects_for_group(group, 'homepage.get_equip') # <<== 该行修改
结果展示:
>>> perms = get_objects_for_group(group, 'homepage.get_equip')
>>> perms
<QuerySet [<Equipment: Equipment object (1)>, <Equipment: Equipment object (2)>]>
>>>