以编程方式创建组:无法访问迁移权限 [英] Programmatically creating a group : Can't access permissions from migration

查看:25
本文介绍了以编程方式创建组:无法访问迁移权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在看到这篇文章后,我尝试通过这个迁移在项目设置中创建自己的组:

After seeing this post, I tried to create my own group at project setup with this migration :

from django.db import migrations
from django.contrib.auth.models import Group, Permission

def create_group(apps, schema_editor):
    group, created = Group.objects.get_or_create(name='thing_managers')
    if created:
        add_thing = Permission.objects.get(codename='add_thing')
        group.permissions.add(add_thing)
        group.save()

class Migration(migrations.Migration):

    dependencies = [
        ('main', '0002_auto_20160720_1809'),
    ]

    operations = [
        migrations.RunPython(create_group),
    ]

但我收到以下错误:

django.contrib.auth.models.DoesNotExist: Permission matching query does not exist.

这是我的模型:

class Thing(models.Model):
    pass

为什么我不能这样做?我该如何解决这个问题?

Why can't I do that? How could I solve this?

我使用 django 1.9.

推荐答案

来自 这张 Django 票,这就是在 Django 3.0.4 中对我有用的方法,并且显然可以在 >=1.9 中使用:

From this Django ticket, here's what worked for me in Django 3.0.4 and apparently will work in >=1.9:

from django.core.management.sql import emit_post_migrate_signal

def create_group(apps, schema_editor):
    # Ensure permissions and content types have been created.
    db_alias = schema_editor.connection.alias
    emit_post_migrate_signal(2, False, db_alias)
    # Now the content types and permissions should exist

    Permission = apps.get_model('auth', 'Permission')
    ...

这篇关于以编程方式创建组:无法访问迁移权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆