Create Group Permissions with Migrations in Django

Here’s an example migration for automatically creating permissions on groups.

This specific install uses both allauth and guardian which is reflected in the migration dependencies, but as this uses Django core Group and Permission objects, it should work without those two modules.

As noted in the gist, YMMV.

# YMMV
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.core.management.sql import emit_post_migrate_signal
from django.db import migrations, models
import django.db.models.deletion
import logging
logger = logging.getLogger(__name__)
role_permissions = {
'Some Role': [
# the perms
],
}
# See https://code.djangoproject.com/ticket/23422
def add_role_permissions(apps, schema_editor):
emit_post_migrate_signal(2, False, 'default')
for r in role_permissions:
role, created = Group.objects.get_or_create(name=r)
logger.info(f'{r} Role retrieved')
for p in role_permissions[r]:
perm, created2 = Permission.objects.get_or_create(codename=p)
role.permissions.add(perm)
logger.info(f'Permitting {r} to {p}')
role.save()
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '__latest__'), # required or emit_post_migrate_signal will bail out
('auth', '__latest__'), # possibly required if using guardian / allauth
('sites', '__latest__'), # required if using allauth or emit_post_migrate_signal will bail out due to missing site
('guardian', '__latest__'), # required if using guardian or emit_post_migrate_signal will bail out due to missing anon user
]
operations = [
migrations.RunPython(add_role_permissions),
]
view raw migration.py hosted with ❤ by GitHub
Published November 6, 2020