[Fixed]-How to add a permission to a user/group during a django migration?

19👍

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

4👍

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

0👍

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

Leave a comment