3

我对 django Guardian 有一些问题。我定义了一个新闻模型

class News(models.Model):
    title = models.CharField(_('Title'), max_length=255)
    slug = models.SlugField(_('Slug'), unique_for_date='pub_date',)

    objects = models.Manager()
    featured = FeaturedNewsManager()

    link = models.URLField(_('Link'), blank=True, null=True,)

    class Meta:
        permissions = (('view_news', _('view news')))

然后我尝试将 view_news 权限分配给我的一位用户,我收到以下错误:

>>> from guardian.shortcuts import assign_perm
>>> g = Group.objects.latest('pk')
>>> n = News.objects.get(pk=4)
>>> assign_perm( 'news.view_news', g, n)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/guardian/shortcuts.py", line 93, in assign_perm
    return model.objects.assign_perm(perm, group, obj)
  File "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/guardian/managers.py", line 90, in assign_perm
    permission = Permission.objects.get(content_type=ctype, codename=perm)
  File "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/db/models/manager.py", line 143, in get
    return self.get_query_set().get(*args, **kwargs)
  File "/home/roberto/.virtualenvs/ve_news/local/lib/python2.7/site-packages/django/db/models/query.py", line 404, in get
    self.model._meta.object_name)
DoesNotExist: Permission matching query does not exist.

我已经尝试迁移我的应用程序,但这似乎并没有解决我的问题。请问有什么帮助吗?

谢谢!

4

2 回答 2

5

尝试做:

python manage.py syncdb --all 

或进行自己的迁移以处理新权限(South 存在一个错误,阻止自动创建迁移以获取监护人权限)

于 2013-10-09T16:40:35.950 回答
1

我相信 syncdb 在这里没有诀窍。我想当您向列表添加更多权限时,您的代码开始工作。

此行有错误:

permissions = (('view_news', _('view news')))

它应该是:

permissions = (('view_news', _('view news')),)

注意缺少的逗号。Permissions 是一个元组的元组,它们是一对类型(权限代码权限描述

编辑

我曾经落入同样的陷阱。避免它的最好方法是即使只有一个权限也可以按如下方式组织代码:

permissions = (
    ('view_news', _('view news')),
)

之后记得按照@Foo Party 和@sogeking 提到的那样做一个同步数据库

$ python manage.py syncdb
于 2013-11-20T05:07:31.663 回答