You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

41 lines
1.5 KiB

2 years ago
2 years ago
2 years ago
2 years ago
2 years ago
  1. from django.contrib.auth.management.commands import createsuperuser
  2. from django.core.management import CommandError
  3. class Command(createsuperuser.Command):
  4. help = "Non-interactively create an admin user"
  5. def add_arguments(self, parser):
  6. super().add_arguments(parser)
  7. parser.add_argument("--password", default=None, help="The password for the admin.")
  8. def handle(self, *args, **options):
  9. password = options.get("password")
  10. username = options.get("username")
  11. if not username:
  12. self.stderr.write("Error: Blank username isn't allowed.")
  13. raise CommandError("--username is required if specifying --password")
  14. if not password:
  15. self.stderr.write("Error: Blank password isn't allowed.")
  16. raise CommandError("--password is required")
  17. if password == "password":
  18. self.stdout.write(self.style.WARNING("Warning: You should change the default password."))
  19. try:
  20. super().handle(*args, **options)
  21. except Exception as err:
  22. if "is already taken" in str(err):
  23. self.stderr.write(f"User {username} already exists.")
  24. else:
  25. raise
  26. database = options.get("database")
  27. db = self.UserModel._default_manager.db_manager(database)
  28. user = db.get(username=username)
  29. user.set_password(password)
  30. message = f"Setting password for User {username}."
  31. self.stdout.write(self.style.SUCCESS(message))
  32. user.save()