Creating groups

13 Views Asked by At

I want to create groups but i am unsure how, is this the correct way? whats the next step after creating this

from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group, Permission

class Command(BaseCommand):
    help = 'Creates initial groups for the application'

    def handle(self, *args, **options):
        # Define the list of group names and descriptions along with associated permissions
        groups_data = [
            {
                'name': 'Students',
                'description': 'Group 1: Students',
                'permissions': ['create_portfolio', 'view_own_portfolio', 'change_own_portfolio', 'delete_own_portfolio']
            },
            {
                'name': 'Lecturers',
                'description': 'Group 2: Lecturers',
                'permissions': ['view_all_portfolios']
            },
            {
                'name': 'Local admin',
                'description': 'Group 3: Local admin',
                'permissions': ['view_all_portfolios']
            },
            {
                'name': 'Organisation admin',
                'description': 'Group 4: Organisation admin',
                'permissions': ['view_all_portfolios']
            },
            # Add more groups as needed
        ]

        # Create groups with associated permissions
        for data in groups_data:
            group, created = Group.objects.get_or_create(name=data['name'])
            if created:
                group.description = data['description']
                group.save()
                # Add permissions to the group
                for perm_codename in data['permissions']:
                    permission = Permission.objects.get(codename=perm_codename)
                    group.permissions.add(permission)
                self.stdout.write(self.style.SUCCESS(f'Group "{group}" created successfully'))
            else:
                self.stdout.write(self.style.WARNING(f'Group "{group}" already exists'))
0

There are 0 best solutions below