How to add a permission to a user/group during a django migration?

浪子不回头ぞ 提交于 2019-12-03 14:11:09
AttributeError: 'StateApps' object has no attribute 'label' in Django 1.10

There is a solution:

for app_config in apps.get_app_configs():
    app_config.models_module = True
    create_permissions(app_config, verbosity=0)
    app_config.models_module = None

EDIT 2018-01-31

This answer will only work until Django 1.9. For Django 1.10 an up, please refer to the answer provided by @anton-lisenkov

Original Answer (Django<1.10)

It turns out I could do the following:

from django.contrib.auth.management import create_permissions

def add_permissions(apps, schema_editor):
    apps.models_module = True

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

Thanks @elad-silver for his answer: https://stackoverflow.com/a/34272647/854868

If you don't have to attach your permission to a personal model you can do it this way:

from django.contrib.auth.models import Permission, ContentType


def add_permission(apps, schema_editor):
    content_type = ContentType.objects.get(app_label='auth', model='user')  # I chose user model but you can edit it
    permission = Permission(
        name='Your permission description',
        codename='your_codename',
        content_type=content_type,
    )
    permission.save()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!