From 5aa4c0b67549f1d7ab649f53ac782d8de3e6a87c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mateusz=20Wi=C4=99ckowski?= Date: Mon, 31 Jul 2023 18:10:32 +0200 Subject: [PATCH] Fixed #34542 -- Made createsuperuser handle required blank fields in non-interactive mode. --- .../management/commands/createsuperuser.py | 6 +++- tests/auth_tests/test_management.py | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index 48994e5371c..6d650cca67e 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -219,11 +219,15 @@ class Command(BaseCommand): for field_name in self.UserModel.REQUIRED_FIELDS: env_var = "DJANGO_SUPERUSER_" + field_name.upper() value = options[field_name] or os.environ.get(env_var) + field = self.UserModel._meta.get_field(field_name) if not value: + if field.blank and ( + options[field_name] == "" or os.environ.get(env_var) == "" + ): + continue raise CommandError( "You must use --%s with --noinput." % field_name ) - field = self.UserModel._meta.get_field(field_name) user_data[field_name] = field.clean(value, None) if field.many_to_many and isinstance(user_data[field_name], str): user_data[field_name] = [ diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 7e0a3012385..872fe75e8ae 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -968,6 +968,36 @@ class CreatesuperuserManagementCommandTestCase(TestCase): stderr=new_io, ) + def test_blank_email_allowed_non_interactive(self): + new_io = StringIO() + + call_command( + "createsuperuser", + email="", + username="joe", + interactive=False, + stdout=new_io, + stderr=new_io, + ) + self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") + u = User.objects.get(username="joe") + self.assertEqual(u.email, "") + + @mock.patch.dict(os.environ, {"DJANGO_SUPERUSER_EMAIL": ""}) + def test_blank_email_allowed_non_interactive_environment_variable(self): + new_io = StringIO() + + call_command( + "createsuperuser", + username="joe", + interactive=False, + stdout=new_io, + stderr=new_io, + ) + self.assertEqual(new_io.getvalue().strip(), "Superuser created successfully.") + u = User.objects.get(username="joe") + self.assertEqual(u.email, "") + def test_password_validation_bypass(self): """ Password validation can be bypassed by entering 'y' at the prompt.