Подтвердить что ты не робот

Добавление новых пользовательских разрешений в Django

Я использую пользовательские разрешения в своих моделях Django следующим образом:

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

Проблема заключается в том, что при добавлении разрешения в список он не добавляется в таблицу auth_permission при запуске syncdb. Что я делаю не так. Если это имеет значение, я использую юг для миграции базы данных.

4b9b3361

Ответ 1

Юг не отслеживает разрешения django.contrib.auth. Подробнее см. билет № 211.

Один из комментариев к билету предполагает, что использование опции --all на syncdb может решить проблему.

Ответ 2

Если вы хотите, чтобы "manage.py migrate" выполнял все (без вызова syncdb -all). Вам необходимо создать новые разрешения с миграцией:

[email protected]> 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'))

Ответ 3

Это сработало для меня:

./manage.py update_permissions

Это django-extensions.

Ответ 4

Вы можете подключиться к сигналу 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)

Ответ 5

Когда я запускаю миграцию со следующим кодом

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