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.

33 lines
1.2 KiB

2 years ago
2 years ago
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 password and not username:
  12. raise CommandError("--username is required if specifying --password")
  13. try:
  14. super().handle(*args, **options)
  15. except Exception as err:
  16. if "is already taken" in str(err):
  17. self.stderr.write(f"User {username} already exists.")
  18. else:
  19. raise
  20. if password:
  21. database = options.get("database")
  22. db = self.UserModel._default_manager.db_manager(database)
  23. user = db.get(username=username)
  24. user.set_password(password)
  25. self.stderr.write(f"Setting password for User {username}.")
  26. user.save()