feat: Add data migration to create groups and assign permissions

This commit is contained in:
earthcomfy 2022-10-23 11:04:17 +03:00 committed by Christopher Charbonneau Wells
parent b50748598b
commit 84d14c3410
2 changed files with 69 additions and 3 deletions

View File

@ -0,0 +1,69 @@
# Generated by Django 4.1.2 on 2022-10-23 07:59
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)
class Migration(migrations.Migration):
dependencies = [
("babybuddy", "0023_alter_settings_timezone"),
]
operations = [migrations.RunPython(add_group_permissions)]

View File

@ -24,9 +24,6 @@ class CommandsTestCase(TransactionTestCase):
self.assertEqual(Child.objects.count(), 1)
def test_createuser(self):
Group.objects.create(name="read_only")
Group.objects.create(name="standard")
call_command(
"createuser",
username="test",