Skip to content

Instantly share code, notes, and snippets.

Created Nov 6, 2020
What would you like to do?
Django: Add Permissions to Groups during Migration
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from 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
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)'{r} Role retrieved')
for p in role_permissions[r]:
perm, created2 = Permission.objects.get_or_create(codename=p)
role.permissions.add(perm)'Permitting {r} to {p}')
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 = [
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment