Files
thrillwiki_django_no_react/apps/accounts/management/commands/setup_groups.py
pacnpal 41b3c86437 Add initial migration for moderation app and resolve seed command issues
- Created an empty migration file for the moderation app to enable migrations.
- Documented the resolution of the seed command failure due to missing moderation tables.
- Identified and fixed a VARCHAR(10) constraint violation in the User model during seed data generation.
- Updated role assignment in the seed command to comply with the field length constraint.
2025-09-25 08:39:05 -04:00

45 lines
1.6 KiB
Python

from django.core.management.base import BaseCommand
from django.contrib.auth.models import Group
from apps.accounts.models import User
from apps.accounts.signals import create_default_groups
class Command(BaseCommand):
help = "Set up default groups and permissions for user roles"
def handle(self, *args, **options):
self.stdout.write("Creating default groups and permissions...")
try:
# Create default groups with permissions
create_default_groups()
# Sync existing users with groups based on their roles
users = User.objects.exclude(role="USER")
for user in users:
group = Group.objects.filter(name=user.role).first()
if group:
user.groups.add(group)
# Update staff/superuser status based on role
if user.role == "SUPERUSER":
user.is_superuser = True
user.is_staff = True
elif user.role in ["ADMIN", "MODERATOR"]:
user.is_staff = True
user.save()
self.stdout.write(
self.style.SUCCESS("Successfully set up groups and permissions")
)
# Print summary
for group in Group.objects.all():
self.stdout.write(f"\nGroup: {group.name}")
self.stdout.write("Permissions:")
for perm in group.permissions.all():
self.stdout.write(f" - {perm.codename}")
except Exception as e:
self.stdout.write(self.style.ERROR(f"Error setting up groups: {str(e)}"))