本文介绍了在迁移中添加django管理员权限:权限匹配查询不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一些组并在手动编写的迁移中为他们分配权限,但是如果我在一个干净的数据库上运行它,它将在运行所有迁移后创建权限。

I wanted to add some groups and assign permissions to them in a manually written migration but if I run it on a clean DB it creates permissions only after running all migrations.

我找到了这张票: https://code.djangoproject.com/ticket/23422
,但我不能在那里发表评论(可能是在GeoDjango文档表达了一些不满之后被禁止),所以我将在下面分析一下解决方案的改进。

I've found this ticket: https://code.djangoproject.com/ticket/23422but I cannot comment there (it's possible I was banned after expressing some discontent with GeoDjango docs), so I'll share an improvement over the solution there below.

推荐答案

Django< = 1.9



Django 1.10 +

只需调用 create_permissions 即可:

from django.contrib.auth.management import create_permissions

apps.models_module = True
create_permissions(apps, verbosity=0)
apps.models_module = None

整个迁移像这样的事情

# coding:utf-8
from django.db import migrations
from django.contrib.auth.models import Permission, Group
from django.contrib.auth.management import create_permissions
from django.contrib.contenttypes.models import ContentType
from django.conf import settings

MODERATORS_PERMISSIONS = ['change_modelname', ]


def add_permissions(apps, schema_editor):
    apps.models_module = True
    create_permissions(apps, verbosity=0)
    apps.models_module = None

    moderators_group = Group.objects.get_or_create(
        name=settings.MODERATORS_GROUP)[0]
    for codename in MODERATORS_PERMISSIONS:
        permission = Permission.objects.get(codename=codename)
        moderators_group.permissions.add(permission)


class Migration(migrations.Migration):

    dependencies = [
        ('contenttypes', '0002_remove_content_type_name'),
        ('thisappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(add_permissions),
    ]

这篇关于在迁移中添加django管理员权限:权限匹配查询不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 23:54