在Django中添加新的自定义权限
我在我的Django模型中使用自定义权限,如下所示:
class T21Turma(models.Model): class Meta: permissions = (("can_view_boletim", "Can view boletim"), ("can_view_mensalidades", "Can view mensalidades"),)
问题是,当我添加一个权限的列表,它不会被添加到auth_permission
表,当我运行syncdb。 我究竟做错了什么。 如果它有任何区别,我正在使用南进行数据库迁移。
南不跟踪django.contrib.auth权限。 请参阅#211门票了解更多信息。
其中一个评论意味着在syncdb上使用--all
选项可以解决问题。
如果你想“manage.py migrate”做一切事情(没有调用syncdb –all)。 您需要通过迁移创build新的权限:
user@host> manage.py datamigration myapp add_perm_foo --freeze=contenttypes --freeze=auth
编辑创build的文件:
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'))
这对我工作:
./manage.py update_permissions
这是一个Django扩展的东西。
您可以连接到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)
当我运行以下代码的迁移
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()