This commit is contained in:
Louis Mazin 2026-09-21 14:41:56 +02:00
parent 7875f21b4d
commit 8f324d99f5

View File

@ -1,6 +1,9 @@
import sys import sys
import logging
from django.apps import AppConfig from django.apps import AppConfig
logger = logging.getLogger(__name__)
class UsersConfig(AppConfig): class UsersConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField' default_auto_field = 'django.db.models.BigAutoField'
name = 'users' name = 'users'
@ -17,10 +20,12 @@ class UsersConfig(AppConfig):
from decouple import config from decouple import config
from django.db import transaction from django.db import transaction
# Don't create/synchronize the configured admin if another # Check if superuser already exists
# superuser already exists. existing_superusers = User.objects.filter(is_superuser=True)
if User.objects.filter(is_superuser=True).exists(): logger.info(f"Found {existing_superusers.count()} existing superusers")
print('A superuser already exists; no admin user was created.')
if existing_superusers.exists():
logger.info('A superuser already exists; no admin user was created.')
return return
username = config('ADMIN_USERNAME', default='').strip() username = config('ADMIN_USERNAME', default='').strip()
@ -29,7 +34,7 @@ class UsersConfig(AppConfig):
last_name = config('ADMIN_LAST_NAME', default='').strip() last_name = config('ADMIN_LAST_NAME', default='').strip()
if not username or not password: if not username or not password:
print('ADMIN_USERNAME and ADMIN_PASSWORD are required; no admin was created.') logger.info('ADMIN_USERNAME and ADMIN_PASSWORD are required; no admin was created.')
return return
with transaction.atomic(): with transaction.atomic():
@ -54,8 +59,8 @@ class UsersConfig(AppConfig):
user.save() user.save()
action = 'created' if created else 'synchronized' action = 'created' if created else 'synchronized'
print(f'Admin user "{username}" {action}.') logger.info(f'Admin user "{username}" {action}.')
except Exception as e: except Exception as e:
# Don't fail the entire Django startup if there's an error # Don't fail the entire Django startup if there's an error
print(f'Error creating admin user: {e}') logger.error(f'Error creating admin user: {e}')