Louis Mazin 8823916d7a nice
2026-10-14 16:04:46 +02:00

46 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Create the initial superuser from environment, without ever updating another."""
from django.db.models import Q
from decouple import config
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand
from django.db import IntegrityError, transaction
class Command(BaseCommand):
help = 'Crée le premier administrateur depuis ADMIN_* si aucun administrateur n’existe.'
def handle(self, *args, **options):
User = get_user_model()
if User.objects.filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
self.stdout.write('Administrateur déjà présent : aucune modification.')
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()
email = config('ADMIN_EMAIL', default='').strip()
if not username or not password:
self.stdout.write(self.style.WARNING('ADMIN_USERNAME ou ADMIN_PASSWORD absent : création ignorée.'))
return
try:
with transaction.atomic():
if User.objects.select_for_update().filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
return
if User.objects.filter(username=username).exists():
self.stdout.write(self.style.WARNING(
'Identifiant déjà utilisé : compte existant inchangé, création ignorée.'))
return
User.objects.create_superuser(
username=username, password=password, email=email,
first_name=first_name, last_name=last_name,
)
except IntegrityError:
# Another container could have initialized the superuser in parallel.
if User.objects.filter(Q(is_superuser=True) | Q(is_staff=True)).exists():
self.stdout.write('Administrateur déjà initialisé par un autre processus.')
return
raise
self.stdout.write(self.style.SUCCESS('Administrateur initial créé.'))