address-service/address/management/commands/ensure_superuser.py

39 lines
1.5 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.

import os
from django.contrib.auth import get_user_model
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = "Создать суперпользователя, если его ещё нет"
def handle(self, *args, **options):
user_model = get_user_model()
if user_model.objects.filter(is_superuser=True).exists():
self.stdout.write("Суперпользователь уже есть")
return
username = os.environ.get("DJANGO_SUPERUSER_USERNAME", "admin").strip() or "admin"
email = os.environ.get("DJANGO_SUPERUSER_EMAIL", "admin@example.com").strip()
password = os.environ.get("DJANGO_SUPERUSER_PASSWORD", "")
if not password:
self.stdout.write(
"Пропуск: нет суперпользователя и не задан DJANGO_SUPERUSER_PASSWORD"
)
return
username_field = user_model.USERNAME_FIELD
if user_model.objects.filter(**{username_field: username}).exists():
raise CommandError(
f"Пользователь {username} уже есть, но не суперпользователь"
)
user_model.objects.create_superuser(
**{
username_field: username,
"email": email,
"password": password,
}
)
self.stdout.write(self.style.SUCCESS(f"Создан суперпользователь {username}"))