mybuddy/babybuddy/migrations/0025_auto_20221023_0821.py

79 lines
1.9 KiB
Python
Raw Normal View History

# Generated by Django 4.1.2 on 2022-10-23 08:21
from django.db import migrations
from django.contrib.auth.models import Group, Permission
import logging
logger = logging.getLogger(__name__)
# MODELS = [model.__name__ for model in apps.get_models()]
MODELS = [
"Tag",
"tagged",
"BMI",
"Child",
"Diaper Change",
"Feeding",
"Head Circumference",
"Height",
"Note",
"Pumping",
"Sleep",
"Temperature",
"Timer",
"Tummy Time",
"Weight",
"user",
]
PERMISSIONS = ["add", "change", "delete", "view"]
def add_group_permissions(apps, schema_editor):
group, created = Group.objects.get_or_create(name="read_only")
perm = []
for model in MODELS:
name = f"Can view {model}"
logging.info(f"Creating {name}...")
try:
perm.append(Permission.objects.get(name=name))
except Permission.DoesNotExist:
logging.warning(f"Permission not found with name {name}.")
continue
group.permissions.add(*perm)
group, created = Group.objects.get_or_create(name="standard")
perm = []
for model in MODELS:
for permission in PERMISSIONS:
name = f"Can {permission} {model}"
logging.info(f"Creating {name}...")
try:
perm.append(Permission.objects.get(name=name))
except Permission.DoesNotExist:
logging.warning(f"Permission not found with name {name}.")
continue
group.permissions.add(*perm)
def revert_migration(apps, schema_editor):
Group.objects.filter(
name__in=[
"read_only",
"standard",
]
).delete()
class Migration(migrations.Migration):
dependencies = [
("babybuddy", "0023_alter_settings_timezone"),
]
operations = [migrations.RunPython(add_group_permissions, revert_migration)]