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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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), | |
] |
Published November 6, 2020