Spaces:
Sleeping
Sleeping
| """ | |
| Management command to create a superuser automatically from environment variables. | |
| Used during Docker startup for Hugging Face Spaces deployment. | |
| Required environment variables (set as Secrets in HF Space settings): | |
| DJANGO_SUPERUSER_USERNAME (default: admin) | |
| DJANGO_SUPERUSER_EMAIL (default: admin@example.com) | |
| DJANGO_SUPERUSER_PASSWORD (required) | |
| """ | |
| import os | |
| from django.core.management.base import BaseCommand | |
| from django.contrib.auth import get_user_model | |
| class Command(BaseCommand): | |
| help = 'Create a superuser from environment variables (non-interactive)' | |
| def handle(self, *args, **options): | |
| User = get_user_model() | |
| username = os.environ.get('DJANGO_SUPERUSER_USERNAME', 'admin') | |
| email = os.environ.get('DJANGO_SUPERUSER_EMAIL', 'admin@example.com') | |
| password = os.environ.get('DJANGO_SUPERUSER_PASSWORD', '') | |
| if not password: | |
| self.stdout.write(self.style.WARNING( | |
| '⚠️ DJANGO_SUPERUSER_PASSWORD is not set. Skipping admin creation.' | |
| )) | |
| return | |
| if User.objects.filter(username=username).exists(): | |
| self.stdout.write(self.style.SUCCESS( | |
| f'✅ Superuser "{username}" already exists. Skipping.' | |
| )) | |
| return | |
| User.objects.create_superuser(username=username, email=email, password=password) | |
| self.stdout.write(self.style.SUCCESS( | |
| f'✅ Superuser "{username}" created successfully.' | |
| )) | |