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.

35 lines
1.2 KiB

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