From 4ff500f2948bfc332b3f4159021cad06e91943d3 Mon Sep 17 00:00:00 2001 From: Christophe Henry Date: Fri, 8 Oct 2021 15:33:09 +0200 Subject: [PATCH] Refs #21755 -- Fixed createsuperuser crash for required foreign keys passed in options in interactive mode. Co-authored-by: Mariusz Felisiak --- .../management/commands/createsuperuser.py | 8 +++--- tests/auth_tests/test_management.py | 26 +++++++++++++++++++ 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/django/contrib/auth/management/commands/createsuperuser.py b/django/contrib/auth/management/commands/createsuperuser.py index 6ab0e5a3b94..4d66e1cca1d 100644 --- a/django/contrib/auth/management/commands/createsuperuser.py +++ b/django/contrib/auth/management/commands/createsuperuser.py @@ -134,12 +134,12 @@ class Command(BaseCommand): self.stderr.write('Error: This field cannot be blank.') continue user_data[field_name] = [pk.strip() for pk in input_value.split(',')] - # Wrap any foreign keys in fake model instances - if field.many_to_one: - fake_user_data[field_name] = field.remote_field.model(input_value) - if not field.many_to_many and field_name not in fake_user_data: + if not field.many_to_many: fake_user_data[field_name] = user_data[field_name] + # Wrap any foreign keys in fake model instances. + if field.many_to_one: + fake_user_data[field_name] = field.remote_field.model(user_data[field_name]) # Prompt for a password if the model has one. while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None: diff --git a/tests/auth_tests/test_management.py b/tests/auth_tests/test_management.py index 575975fd902..8cd7b378c0f 100644 --- a/tests/auth_tests/test_management.py +++ b/tests/auth_tests/test_management.py @@ -505,6 +505,32 @@ class CreatesuperuserManagementCommandTestCase(TestCase): test(self) + @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithFK') + def test_fields_with_fk_via_option_interactive(self): + new_io = StringIO() + group = Group.objects.create(name='mygroup') + email = Email.objects.create(email='mymail@gmail.com') + + @mock_inputs({'password': 'nopasswd'}) + def test(self): + call_command( + 'createsuperuser', + interactive=True, + username=email.pk, + email=email.email, + group=group.pk, + stdout=new_io, + stdin=MockTTY(), + ) + + command_output = new_io.getvalue().strip() + self.assertEqual(command_output, 'Superuser created successfully.') + u = CustomUserWithFK._default_manager.get(email=email) + self.assertEqual(u.username, email) + self.assertEqual(u.group, group) + + test(self) + @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithM2m') def test_fields_with_m2m(self): new_io = StringIO()