71

我在我的 Django 模型中使用自定义权限,如下所示:

class T21Turma(models.Model):
    class Meta:
        permissions = (("can_view_boletim", "Can view boletim"),
                       ("can_view_mensalidades", "Can view mensalidades"),)

auth_permission问题是当我向列表添加权限时,当我运行 syncdb 时它不会被添加到表中。我究竟做错了什么。如果这有什么不同,我将使用 south 进行数据库迁移。

4

5 回答 5

60

South 不跟踪 django.contrib.auth 权限。有关更多信息,请参见票证 #211

票证上的一条评论表明,使用--allsyncdb 上的选项可能会解决问题。

于 2009-11-16T14:04:32.763 回答
48

如果您希望“manage.py migrate”完成所有操作(不调用 syncdb --all)。您需要通过迁移创建新权限:

user@host> manage.py datamigration myapp add_perm_foo --freeze=contenttypes --freeze=auth

编辑创建的文件:

class Migration(DataMigration):

    def forwards(self, orm):
        "Write your forwards methods here."
        ct, created = orm['contenttypes.ContentType'].objects.get_or_create(
            model='mymodel', app_label='myapp') # model must be lowercase!
        perm, created = orm['auth.permission'].objects.get_or_create(
            content_type=ct, codename='mymodel_foo', defaults=dict(name=u'Verbose Name'))
于 2011-05-27T08:18:42.830 回答
27

这对我有用:

./manage.py update_permissions

这是一个django 扩展的东西。

于 2013-04-30T20:51:42.743 回答
20

您可以连接到post_migrate信号以便在迁移后更新权限。我使用以下代码,从Dev with Passion稍作修改,最初来自django-extensions

# Add to your project-level __init__.py

from south.signals import post_migrate

def update_permissions_after_migration(app,**kwargs):
    """
    Update app permission just after every migration.
    This is based on app django_extensions update_permissions management command.
    """
    from django.conf import settings
    from django.db.models import get_app, get_models
    from django.contrib.auth.management import create_permissions

    create_permissions(get_app(app), get_models(), 2 if settings.DEBUG else 0)

post_migrate.connect(update_permissions_after_migration)
于 2012-08-11T11:48:10.397 回答
2

当我使用以下代码运行迁移时

ct, created = orm['contenttypes.ContentType'].objects.get_or_create(model='mymodel',     app_label='myapp') # model must bei lowercase!
perm, created = orm['auth.permission'].objects.get_or_create(content_type=ct, codename='mymodel_foo')

我得到以下错误

File "C:\Python26\lib\site-packages\south-0.7.3-py2.6.egg\south\orm.py", line 170, in  __getitem__
raise KeyError("The model '%s' from the app '%s' is not available in this migration." % (model, app))
KeyError: "The model 'contenttype' from the app 'contenttypes' is not available in this migration."

为了防止这个错误,我修改了代码

from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission

class Migration(DataMigration):

    def forwards(self, orm):
        "Write your forwards methods here."
        ct = ContentType.objects.get(model='mymodel', app_label='myapp') 
        perm, created = Permission.objects.get_or_create(content_type=ct, codename='mymodel_foo')
        if created:
            perm.name=u'my permission description'
            perm.save()
于 2011-08-04T05:15:38.917 回答