Add: managment command to create admin user
This commit is contained in:
parent
9c04a9b025
commit
2efb85edf3
1 changed files with 46 additions and 0 deletions
46
backend/api/user/management/commands/createadmin.py
Normal file
46
backend/api/user/management/commands/createadmin.py
Normal 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.")
|
||||
)
|
Loading…
Add table
Reference in a new issue