我正在尝试添加两个组并授予他们Django项目的权限。但我一直收到错误:
ContentType匹配查询不存在。
我正在跑步: Django 1.5.4 Python 2.7.3 南0.8.2 PostreSQL 9.3
这是我的代码:
import django
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from .models import Flavor
def add_groups():
# Create User Groups
special_users = Group(name='Special Users')
special_users.save()
really_special_users = Group(name='Super Special Users')
really_special_users.save()
def add_permissions():
# Define a View permission for the 1st group, and a View/Modify permission for the 2nd group
somemodel_ct = ContentType.objects.get(app_label='flavors', model='flavors_flavor')
can_view = Permission(name='Can View', codename='can_view_something', content_type=somemodel_ct)
can_view.save()
can_modify = Permission(name='Can Modify', codename='can_modify_something', content_type=somemodel_ct)
can_modify.save()
def give_perm_to_groups():
# Associate these two permissions now with a Group
special_users.permissions.add(can_view)
really_special_users.permissions = [can_view, can_modify]
我可以运行add_groups()。现在正在使用add_permissions()。我相信这与Postgres中的灯具有关,但不确定如何添加它们或者这是否是确切的问题?
由于
以下是整个错误追溯:
>>> add_permissions()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/Yuki_Aaron/Documents/djcode/demoproject/flavors/groups.py", line 16, in add_permissions
somemodel_ct = ContentType.objects.get(app_label='flavors', model='flavors_flavor')
File "/Users/Yuki_Aaron/Documents/virtualenvs/django1.5/lib/python2.7/site-packages/django/db/models/manager.py", line 143, in get
return self.get_query_set().get(*args, **kwargs)
File "/Users/Yuki_Aaron/Documents/virtualenvs/django1.5/lib/python2.7/site-packages/django/db/models/query.py", line 404, in get
self.model._meta.object_name)
DoesNotExist: ContentType matching query does not exist.
答案 0 :(得分:2)
更改此行:
somemodel_ct = ContentType.objects.get(app_label='flavors', model='flavors_flavor')
由:
somemodel_ct = ContentType.objects.get(app_label='flavors', model='flavor')
指定模型时似乎有问题
答案 1 :(得分:1)
我要做的第一件事就是将somemodel_ct
更改为:
somemodel_ct = ContentType.objects.get(app_label='flavors', model='flavor')
第二件事是错误是由于我需要为我的模型添加权限,以便django.contrib.auth.models
.... Permission
和Group
能够在模型中查找已定义的权限,然后关联回ContentType
。以下是我添加到models.py
以使其正常运行的代码:
class Flavor(models.Model):
...
class Meta:
permissions = (
('can_view', 'Can View'),
('can_modify', 'Can Modify'),
)
这样,我的Flavor
模型可以在Permission
表中查找权限。这就是为什么它说ContentType: no matching query
,因为我没有将class Meta: permissions
包含在我的实际Flavor
模型中。
感谢您的帮助!