运行迁移时,“StateApps”对象没有属性“label”

时间:2017-09-20 08:14:42

标签: django django-migrations django-permissions

当我尝试运行此迁移时:

def add_user_data(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Permission = apps.get_model(
        'auth', 'Permission')
    Profile = apps.get_model('user', 'Profile')
    User = apps.get_model('user', 'User')
    andrew_user = User.objects.create(
        email='django@jambonsw.com',
        password=make_password('hunter2'),
        is_active=True,
        is_staff=True,
        is_superuser=True)
    andrew_profile = Profile.objects.create(
        user=andrew_user,
        name='Andrew',
        slug='andrew',
        about='The author of this site!')
    ada_user = User.objects.create(
        email='ada@djangogirls.org',
        password=make_password('algorhythm'),
        is_active=True,
        is_staff=True,
        is_superuser=False)
    ada_profile = Profile.objects.create(
        user=ada_user,
        name='Ada Lovelace',
        slug='the_countess',
        about=(
            ' '))
    contributors = Group.objects.create(
        name='contributors')
    ada_user.groups.add(contributors)
    permissions = [
        'add_post',
        'change_post',
    ]
    for perm in permissions:
        contributors.permissions.add(
            Permission.objects.get(
                codename=perm,
                content_type__app_label='blog'))


def remove_user_data(apps, schema_editor):
    Group = apps.get_model('auth', 'Group')
    Profile = apps.get_model('user', 'Profile')
    User = apps.get_model('user', 'User')
    Profile.objects.get(slug='andrew').delete()
    Profile.objects.get(
        slug='the_countess').delete()
    User.objects.get(
        email='django@jambonsw.com').delete()
    User.objects.get(
        email='ada@djangogirls.org').delete()
    Group.objects.get(
        name='contributors').delete()


class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0005_post_permissions'),
        ('user', '0002_profile'),
    ]

    operations = [
        migrations.RunPython(
            add_user_data,
            remove_user_data)
    ]

我遇到了这个错误:

  

AttributeError:'StateApps'对象没有属性'label'

我真的不知道'StateApps'的作用。但是,正如错误消息所述,它与分配权限有关。有人可以帮忙吗?这段代码来自使用Django 1.8的教程,所以我认为它是django 1.11,这使得代码出错。

1 个答案:

答案 0 :(得分:1)

更改git init中的generate_permissions功能:

blog/migrations/0005_post_permissions.py

使用django 2.1可以为我工作