以编程方式创建一个组:无法访问迁移的权限。

时间:2021-08-16 19:23:27

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),
    ]

But I got the following error :

但我犯了如下错误:

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

Here is my model :

这是我的模型:

class Thing(models.Model):
    pass

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

为什么我不能这么做?我怎么解决这个问题?

I use django 1.9.

我使用django 1.9。

1 个解决方案

#1


1  

Permissions are created in a post_migrate signal. They don't exist the first time migrations are run after a new model is added. It is probably easiest to run the post_migrate signal handler manually:

权限是在post_migrate信号中创建的。在添加新模型之后第一次运行迁移时,它们并不存在。手动运行post_migrate信号处理程序可能是最简单的:

from django.contrib.auth.management import create_permissions

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

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

create_permissions checks for existing permissions, so this won't create any duplicates.

create_permissions检查现有权限,因此不会创建任何副本。

#1


1  

Permissions are created in a post_migrate signal. They don't exist the first time migrations are run after a new model is added. It is probably easiest to run the post_migrate signal handler manually:

权限是在post_migrate信号中创建的。在添加新模型之后第一次运行迁移时,它们并不存在。手动运行post_migrate信号处理程序可能是最简单的:

from django.contrib.auth.management import create_permissions

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

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

create_permissions checks for existing permissions, so this won't create any duplicates.

create_permissions检查现有权限,因此不会创建任何副本。