From 048fbf9c8919f3838f427f7b0fccf10428530de7 Mon Sep 17 00:00:00 2001 From: Christophe Henry Date: Fri, 8 Oct 2021 15:33:09 +0200 Subject: [PATCH] [4.0.x] Fixed #33178 -- Made createsuperuser validate required fields passed in options in interactive mode. Backport of b1b26b37aff0c80d6abdf15c5ffdf0440a9a1d6a from main. --- .../management/commands/createsuperuser.py | 2 ++ tests/auth_tests/test_management.py | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index 4d66e1cca1..42898e6744 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -124,6 +124,8 @@ class Command(BaseCommand): for field_name in self.UserModel.REQUIRED_FIELDS: field = self.UserModel._meta.get_field(field_name) user_data[field_name] = options[field_name] + if user_data[field_name] is not None: + user_data[field_name] = field.clean(user_data[field_name], None) while user_data[field_name] is None: message = self._get_input_message(field) input_value = self.get_input_data(field, message) diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 8cd7b378c0..7e44a5314f 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -531,6 +531,29 @@ class CreatesuperuserManagementCommandTestCase(TestCase): test(self) + @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithFK') + def test_validate_fk_via_option_interactive(self): + email = Email.objects.create(email='mymail@gmail.com') + Group.objects.all().delete() + nonexistent_group_id = 1 + msg = f'group instance with id {nonexistent_group_id} does not exist.' + + @mock_inputs({ + 'password': 'nopasswd', + 'Username (Email.id): ': email.pk, + 'Email (Email.email): ': email.email, + }) + def test(self): + with self.assertRaisesMessage(CommandError, msg): + call_command( + 'createsuperuser', + group=nonexistent_group_id, + stdin=MockTTY(), + verbosity=0, + ) + + test(self) + @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithM2m') def test_fields_with_m2m(self): new_io = StringIO()