import sys import logging from django.apps import AppConfig logger = logging.getLogger(__name__) class UsersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'users' def ready(self): # Only run this logic when Django is ready and not during migrations/tests if 'test' in sys.argv or 'migrate' in sys.argv or 'makemigrations' in sys.argv: return # Only run when the server is actually starting if 'runserver' in sys.argv: try: from .models import User from decouple import config from django.db import transaction # Check if superuser already exists existing_superusers = User.objects.filter(is_superuser=True) logger.info(f"Found {existing_superusers.count()} existing superusers") if existing_superusers.exists(): logger.info('A superuser already exists; no admin user was created.') return username = config('ADMIN_USERNAME', default='').strip() password = config('ADMIN_PASSWORD', default='') first_name = config('ADMIN_FIRST_NAME', default='').strip() last_name = config('ADMIN_LAST_NAME', default='').strip() if not username or not password: logger.info('ADMIN_USERNAME and ADMIN_PASSWORD are required; no admin was created.') return with transaction.atomic(): user, created = User.objects.get_or_create( username=username, defaults={ 'first_name': first_name, 'last_name': last_name, 'is_staff': True, 'is_superuser': True, }, ) if created: user.set_password(password) else: user.first_name = first_name user.last_name = last_name user.is_staff = True user.is_superuser = True user.save() action = 'created' if created else 'synchronized' logger.info(f'Admin user "{username}" {action}.') except Exception as e: # Don't fail the entire Django startup if there's an error logger.error(f'Error creating admin user: {e}')