Skip to content

Instantly share code, notes, and snippets.

@solace
Created Nov 6, 2020
Embed
What would you like to do?
Django: Add Permissions to Groups during Migration
# 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),
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment