Refs #21755 -- Fixed createsuperuser crash for required foreign keys passed in options in interactive mode.

Co-authored-by: Mariusz Felisiak <felisiak.mariusz@gmail.com>
This commit is contained in:
Christophe Henry 2021-10-08 15:33:09 +02:00 committed by Mariusz Felisiak
parent da266b3c5c
commit 4ff500f294
2 changed files with 30 additions and 4 deletions

View File

@ -134,12 +134,12 @@ class Command(BaseCommand):
self.stderr.write('Error: This field cannot be blank.') self.stderr.write('Error: This field cannot be blank.')
continue continue
user_data[field_name] = [pk.strip() for pk in input_value.split(',')] 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] 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. # Prompt for a password if the model has one.
while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None: while PASSWORD_FIELD in user_data and user_data[PASSWORD_FIELD] is None:

View File

@ -505,6 +505,32 @@ class CreatesuperuserManagementCommandTestCase(TestCase):
test(self) 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') @override_settings(AUTH_USER_MODEL='auth_tests.CustomUserWithM2m')
def test_fields_with_m2m(self): def test_fields_with_m2m(self):
new_io = StringIO() new_io = StringIO()