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.

34 lines
1.2 KiB

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