Skip to content

Instantly share code, notes, and snippets.

@acpmasquerade
Created April 21, 2025 11:15
Show Gist options
  • Save acpmasquerade/7c9d876fd1854d4a867a5070729adf4f to your computer and use it in GitHub Desktop.
Save acpmasquerade/7c9d876fd1854d4a867a5070729adf4f to your computer and use it in GitHub Desktop.
Sync and Dump Permissions with the corresponding Content Type in Django
"""
Permission Map Generator and Loader
This script generates a permission map from one system and helps to load it into another system with exact permission mapping,
regardless of the primary keys in the new system. It also verifies if there are any mismatches between the loaded permissions
and the original dump.
Functions:
dump_groups_and_permissions: Dumps the current permission map from the system.
load_groups_and_permissions: Loads a permission map into the system and verifies for any mismatches.
Usage:
1. Call dump_groups_and_permissions() to generate a permission map from the current system.
2. Call load_groups_and_permissions() with the generated permission map to load it into another system.
"""
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
def dump_groups_and_permissions():
permissions_dump = []
for g in Group.objects.all():
group_perm_maps = [g.name, list(g.permissions.all().values_list('codename', 'content_type__model', 'content_type__app_label'))]
print(group_perm_maps)
permissions_dump.append(group_perm_maps)
return permissions_dump
def load_groups_and_permissions(permissions_dump):
for l in permissions_dump:
grp = l[0]
perms = l[1]
group, _ = Group.objects.get_or_create(name=grp)
print("")
print(f"[Group] {grp}")
print("--------------------------------")
for p in perms:
try:
ctype = ContentType.objects.get(model=p[1], app_label=p[2])
perm = Permission.objects.get(codename=p[0], content_type=ctype)
check = group.permissions.filter(id=perm.id).count()
if check == 0:
print(f"Adding {grp}.{p[0]}")
group.permissions.add(perm)
else:
print(f"SKIPPED !! {grp}.{p[0]} already exists")
except ContentType.DoesNotExist:
print(f"Content type {p[1], p[2]} not found")
except Permission.DoesNotExist:
print(f"Permission {p[1], p[0]} not found")
except Exception as e:
print(e)
print(f"Permission {p[1], p[0]} not found: {e}")
# mismatch check
if len(perms) == group.permissions.count():
print(f"--\nOK !! SYNCED !! {grp} has {group.permissions.count()} permissions, and {len(perms)} permissions in the dump\n--")
else:
print(f"--\nMISMATCH !! {grp} has {group.permissions.count()} permissions, but {len(perms)} permissions in the dump\n--")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment