Add: managment command to create admin user

This commit is contained in:
Aroy-Art 2025-04-05 21:22:59 +02:00
parent 9c04a9b025
commit 2efb85edf3
Signed by: Aroy
GPG key ID: 583642324A1D2070

View file

@ -0,0 +1,46 @@
import os
from django.core.management.base import BaseCommand
from django.contrib.auth import get_user_model
from api.user.models import UserProfile
class Command(BaseCommand):
"""
Creates an admin user non-interactively if it doesn't exist.
Reads credentials from environment variables:
- DJANGO_SUPERUSER_USERNAME
- DJANGO_SUPERUSER_PASSWORD
- DJANGO_SUPERUSER_EMAIL
"""
help = "Creates a superuser non-interactively if it does not exist."
def handle(self, *args, **options):
User = get_user_model()
username = os.environ.get("DJANGO_SUPERUSER_USERNAME")
password = os.environ.get("DJANGO_SUPERUSER_PASSWORD")
email = os.environ.get("DJANGO_SUPERUSER_EMAIL")
if not username or not password or not email:
self.stdout.write(
self.style.WARNING(
"Skipping superuser creation: DJANGO_SUPERUSER_USERNAME, "
"DJANGO_SUPERUSER_PASSWORD, and DJANGO_SUPERUSER_EMAIL must be set."
)
)
return # Exit the command gracefully
if not User.objects.filter(username=username).exists():
self.stdout.write(self.style.SUCCESS(f"Creating superuser: {username}"))
try:
User.objects.create_superuser(
username=username, email=email, password=password
)
UserProfile.objects.create(user=User.objects.get(username=username))
self.stdout.write(self.style.SUCCESS("Superuser created successfully."))
except Exception as e:
self.stderr.write(self.style.ERROR(f"Error creating superuser: {e}"))
else:
self.stdout.write(
self.style.NOTICE(f"Superuser '{username}' already exists.")
)