Adding django admin permissions in a migration: Permission matching query does not exist
In django 1.10 the following code could be used:
from django.contrib.auth.management import create_permissionsdef 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
Django <= 1.9
see another answer for Django 1.10+
It's enough to call create_permissions
:
from django.contrib.auth.management import create_permissionsapps.models_module = Truecreate_permissions(apps, verbosity=0)apps.models_module = None
The whole migration being something like this
# coding:utf-8from django.db import migrationsfrom django.contrib.auth.models import Permission, Groupfrom django.contrib.auth.management import create_permissionsfrom django.contrib.contenttypes.models import ContentTypefrom django.conf import settingsMODERATORS_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), ]
And if you want something that will work on any version (or that will keep working when you upgrade):
from django.contrib.auth.management import create_permissionsversion = django.VERSIONif version[0] >= 1 and django.VERSION[1] > 9: 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 = Noneelse: apps.models_module = True create_permissions(apps, verbosity=0) apps.models_module = None