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

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

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

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

33940 次浏览

South 不跟踪 django.Contrib.auth 权限。请参阅 211号票了解更多信息。

票据上的一条注释表明,在 syncdb 上使用 --all选项可以解决这个问题。

如果您希望“ manage.py 侯选人”完成所有事情(不调用 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'))

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

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()

您可以连接到 post_migrate信号,以便在迁移后更新权限。我使用下面的代码,稍微修改了 有激情的戴夫和原来的 姜戈接发

# 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)

这对我很有效:

./manage.py update_permissions

这是 姜戈接发的东西。