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.

31 lines
1.1 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 IntegrityError:
  18. self.stderr.write(f'User {username} already exists.')
  19. if password:
  20. database = options.get('database')
  21. db = self.UserModel._default_manager.db_manager(database)
  22. user = db.get(username=username)
  23. user.set_password(password)
  24. user.save()