Repository URL to install this package:
|
Version:
0.0.1 ▾
|
from django.contrib.auth import get_permission_codename
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from ..models import ProgrammaticGroup
def add_perm_groups(groups_def, printf=print, printf_error=print):
for group_name in groups_def:
group, created = Group.objects.get_or_create(name=group_name)
if created:
ProgrammaticGroup.objects.create(group=group)
printf(f"Created group {group}")
for model_cls in groups_def[group_name]:
content_type = ContentType.objects.get_for_model(model_cls) if model_cls else None
for action_name in groups_def[group_name][model_cls]:
codename = get_permission_codename(action_name, model_cls._meta) if model_cls else action_name
try:
# Find permission object and add to group
if content_type:
perm = Permission.objects.get(codename=codename, content_type=content_type)
else:
perm = Permission.objects.get(codename=codename)
group.permissions.add(perm)
printf(f"Added {codename} to group {group}")
except Permission.DoesNotExist:
printf_error(f"{codename} not found")