以编程方式创建组:无法从迁移访问权限 [英] Programmatically creating a group : Can't access permissions from migration
本文介绍了以编程方式创建组:无法从迁移访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在看到这篇文章后,我尝试通过此迁移在项目设置中创建自己的组:
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 。
推荐答案
权限是在 post_migrate
信号中创建的。在添加新模型后,首次迁移运行时不存在。运行 post_migrate可能是最简单的方法 信号处理程序手动:
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:
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
检查现有权限,因此不会创建任何重复项。
create_permissions
checks for existing permissions, so this won't create any duplicates.
这篇关于以编程方式创建组:无法从迁移访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文