Django在迁移中插入权限

时间:2018-01-13 10:24:57

标签: python django permissions migration database-migration

我需要在迁移中填充auth_group_permission表。我用这段代码创建了一个迁移:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-12-05 10:07
from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import Group, Permission
from django.contrib.auth.management import create_permissions

def add_group_permissions(apps, schema_editor):
    for app_config in apps.get_app_configs():
        create_permissions(app_config, apps=apps, verbosity=0)

    #Workers
    group, created = Group.objects.get_or_create(name='Workers')   
    can_add_worker_task = Permission.objects.get(codename='add_worker_task')
    group.permissions.add(can_add_worker_task)
    group.save()

class Migration(migrations.Migration):
    dependencies = [
        ('crowdsourcing', '0005_add_view_permission'),
        ('auth', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_group_permissions),
    ]

但是当我执行“python manage.py migrate”命令时,我收到了这个错误:“django.contrib.auth.models.DoesNotExist:权限匹配查询不存在”。我认为问题是“auth_permission”表仍然是空的。我可以解决吗?

1 个答案:

答案 0 :(得分:1)

我用这段代码解决了:

<forms loginUrl="/account/login" name="authy" path="/" slidingExpiration="true" cookieless="UseCookies"/>