2

私は、次の移行を実行したいと思います:移行の最後の行でdjangoの移行中にユーザー/グループに権限を追加するにはどうすればいいですか?

# -*- coding: utf-8 -*- 
from __future__ import unicode_literals 
from django.contrib.auth.models import Permission 
from django.db import migrations 
from django.conf import settings 
from django.contrib.auth.models import Group, User 


def add_api_group(apps, schema_editor): 

    Group.objects.create(name=settings.API_USER_GROUP) 
    # get_or_create returns a tuple, not a Group 
    group = Group.objects.get(name=settings.API_USER_GROUP) 
    permissions = Permission.objects.filter(codename__in = [ 
     'add_topic', 
    ]) 
    group.permissions.add(*permissions) 


def add_api_user(apps, schema_editor): 

    user = User.objects.create_user(username=settings.API_USER, password=settings.API_USER_PASSWORD) 
    group = Group.objects.get(name=settings.API_USER_GROUP) 
    user.groups.add(group) 

class Migration(migrations.Migration): 

    dependencies = [ 
     ('nd_content', '0001_initial'), 
    ] 

    operations = [ 
     migrations.RunPython(add_api_group), 
     migrations.RunPython(add_api_user) 
    ] 

を、私は実行を停止し、データベースの状態を見て、エラーを発行しました。問題はテーブルauth_permissionが他のモジュールのモデルのパーミッションをまだ持っていないことですが、この他のモジュールはこの移行の依存として登録されています。

不足している権限を確認できるのは、すべての移行が実行された後にのみ追加されるようです。

答えて

4
AttributeError: 'StateApps' object has no attribute 'label' in Django 1.10 

私は解決策:

for app_config in apps.get_app_configs(): 
    app_config.models_module = True 
    create_permissions(app_config, verbosity=0) 
    app_config.models_module = None 
3

EDIT 2018年1月31日

この回答はDjangoの1.9まで動作します。 Djangoの1.10アップのために、@のアントン・lisenkov

オリジナル回答によって提供さanswerを参照してください(ジャンゴ< 1.10)

それは私が次の操作を行うことができ判明:

from django.contrib.auth.management import create_permissions 

def add_permissions(apps, schema_editor): 
    apps.models_module = True 

    create_permissions(apps, verbosity=0) 
    apps.models_module = None 

彼の答えをありがとう@ ELAD-銀:ありhttps://stackoverflow.com/a/34272647/854868

関連する問題