diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index f9a198f0d4..7e19ef9955 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -68,6 +68,7 @@ class Command(BaseCommand): # Same as user_data but with foreign keys as fake model instances # instead of raw IDs. fake_user_data = {} + verbose_field_name = self.username_field.verbose_name # Do quick and dirty validation if --noinput if not options['interactive']: @@ -96,7 +97,6 @@ class Command(BaseCommand): raise NotRunningInTTYException("Not running in a TTY") # Get a username - verbose_field_name = self.username_field.verbose_name while username is None: input_msg = capfirst(verbose_field_name) if default_username: @@ -121,6 +121,9 @@ class Command(BaseCommand): self.stderr.write("Error: That %s is already taken." % verbose_field_name) username = None + if not username: + raise CommandError('%s cannot be blank.' % capfirst(verbose_field_name)) + for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options[field_name] diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index c43091d932..5463707dad 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -523,6 +523,22 @@ class CreatesuperuserManagementCommandTestCase(TestCase): test(self) + def test_blank_username(self): + """Creation fails if --username is blank.""" + new_io = StringIO() + + def test(self): + with self.assertRaisesMessage(CommandError, 'Username cannot be blank.'): + call_command( + 'createsuperuser', + username='', + stdin=MockTTY(), + stdout=new_io, + stderr=new_io, + ) + + test(self) + def test_invalid_username(self): """Creation fails if the username fails validation.""" user_field = User._meta.get_field(User.USERNAME_FIELD)