在Django中添加新的自定义权限

时间:2009-11-16 12:51:40

标签: django django-south django-permissions

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

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

问题是,当我向列表添加权限时,当我运行syncdb时,它不会被添加到auth_permission表中。我究竟做错了什么。如果它有任何区别我在南方使用数据库迁移。

5 个答案:

答案 0 :(得分:59)

South不会跟踪django.contrib.auth权限。有关详细信息,请参阅ticket #211

该故障单上的一条评论表明,在syncdb上使用--all选项可以解决问题。

答案 1 :(得分: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'))

答案 2 :(得分:27)

这对我有用:

./manage.py update_permissions

这是django-extensions事。

答案 3 :(得分: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)

答案 4 :(得分: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()