diff --git a/bsmain/management/commands/prestart.py b/bsmain/management/commands/prestart.py index c83062e..0b6cc4a 100644 --- a/bsmain/management/commands/prestart.py +++ b/bsmain/management/commands/prestart.py @@ -12,16 +12,24 @@ User = get_user_model() class Command(BaseCommand): help = "Pre-start command to run before the server starts." + def _create_superuser_if_needed(self): + if not os.getenv("CREATE_SUPERUSER", ""): + return + + if ":" not in os.getenv("CREATE_SUPERUSER"): + raise ValueError("CREATE_SUPERUSER should be in the format 'username:password'") + + username, password = os.getenv("CREATE_SUPERUSER").split(":") + + if User.objects.all().exists(): + print("Superuser not created: user(s) already exist.") + return + + User.objects.create_superuser(username=username, password=password) + print(f"Superuser created: {username}") + def handle(self, *args, **options): - if os.getenv("CREATE_SUPERUSER", ""): - if ":" not in os.getenv("CREATE_SUPERUSER"): - raise ValueError("CREATE_SUPERUSER should be in the format 'username:password'") - - username, password = os.getenv("CREATE_SUPERUSER").split(":") - - if not User.objects.filter(username=username).exists(): - User.objects.create_superuser(username=username, password=password) - print(f"Superuser created: {username}") + self._create_superuser_if_needed() # Similar considerations apply here as those which are documented in bugsink.views._phone_home(). # By putting this in prestart, we add one more location to the list of kick-off locations; with the added