mcreatesuperuser.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from optparse import make_option
  2. from django.contrib.auth import get_user_model
  3. from django.core.exceptions import ValidationError
  4. from django.core.management.base import BaseCommand, CommandError
  5. from django.db import DEFAULT_DB_ALIAS
  6. from django.utils.encoding import force_str
  7. from django.utils.six.moves import input
  8. class NotRunningInTTYException(Exception):
  9. pass
  10. class Command(BaseCommand):
  11. help = 'Used to create a superuser.'
  12. def __init__(self, *args, **kwargs):
  13. super(Command, self).__init__(*args, **kwargs)
  14. self.option_list = BaseCommand.option_list + (
  15. make_option('--username', dest='username', default=None,
  16. help='Specifies the username for the superuser.'),
  17. make_option('--email', dest='email', default=None,
  18. help='Specifies the username for the superuser.'),
  19. make_option('--password', dest='password', default=None,
  20. help='Specifies the username for the superuser.'),
  21. make_option('--noinput', action='store_false', dest='interactive', default=True,
  22. help=('Tells Miago to NOT prompt the user for input of any kind. '
  23. 'You must use --username with --noinput, along with an option for '
  24. 'any other required field. Superusers created with --noinput will '
  25. ' not be able to log in until they\'re given a valid password.')),
  26. make_option('--database', action='store', dest='database',
  27. default=DEFAULT_DB_ALIAS, help='Specifies the database to use. Default is "default".'),
  28. )
  29. def handle(self, *args, **options):
  30. User = get_user_model()
  31. username = options.get('username')
  32. email = options.get('email')
  33. password = options.get('password')
  34. interactive = options.get('interactive')
  35. if not interactive:
  36. pass
  37. else:
  38. try:
  39. if hasattr(self.stdin, 'isatty') and not self.stdin.isatty():
  40. raise NotRunningInTTYException("Not running in a TTY")
  41. while username is None:
  42. break
  43. while email is None:
  44. break
  45. while password is None:
  46. break
  47. except KeyboardInterrupt:
  48. self.stderr.write("\nOperation cancelled.")
  49. sys.exit(1)
  50. except NotRunningInTTYException:
  51. self.stdout.write(
  52. "Superuser creation skipped due to not running in a TTY. "
  53. "You can run `manage.py createsuperuser` in your project "
  54. "to create one manually."
  55. )