Adding django admin permissions in a migration: Permission matching query does not exist

int_ua picture int_ua · Jul 31, 2015 · Viewed 7.3k times · Source

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.

I've found this ticket: https://code.djangoproject.com/ticket/23422 but 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.

Answer

xuhcc picture xuhcc · Oct 17, 2016

In django 1.10 the following code could be used:

from django.contrib.auth.management import create_permissions

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