import sys from django.apps import AppConfig from django.core.management import execute_from_command_line 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: # Defer the superuser creation to avoid database access during app initialization # This prevents the Django warning about accessing database during app initialization import threading import time def create_superuser_if_needed(): # Wait a bit to ensure Django is fully ready time.sleep(0.1) 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) print(f"Found {existing_superusers.count()} existing superusers") if existing_superusers.exists(): print('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: print('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' print(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}') # Start the superuser creation in a separate thread to avoid the warning thread = threading.Thread(target=create_superuser_if_needed, daemon=True) thread.start()