From e804a07d76fc85468f27f7130ae1442fabcd650d Mon Sep 17 00:00:00 2001 From: hesham942 Date: Fri, 14 Mar 2025 15:16:38 +0200 Subject: [PATCH] Fixed #36252 -- Handled duplicate automatic imports in the shell command. --- django/core/management/commands/shell.py | 4 ++-- docs/howto/custom-shell.txt | 3 ++- tests/shell/tests.py | 5 +++++ 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/django/core/management/commands/shell.py b/django/core/management/commands/shell.py index 89d12ce6b8..132e7f89d2 100644 --- a/django/core/management/commands/shell.py +++ b/django/core/management/commands/shell.py @@ -185,8 +185,8 @@ class Command(BaseCommand): else: module = None name = path - - auto_imports[module].append((name, obj)) + if (name, obj) not in auto_imports[module]: + auto_imports[module].append((name, obj)) namespace = { name: obj for items in auto_imports.values() for name, obj in items diff --git a/docs/howto/custom-shell.txt b/docs/howto/custom-shell.txt index 312a38162b..c1632849b5 100644 --- a/docs/howto/custom-shell.txt +++ b/docs/howto/custom-shell.txt @@ -55,7 +55,8 @@ Running this customized ``shell`` command with ``verbosity=2`` would show: from django.urls import resolve, reverse If an overridden ``shell`` command includes paths that cannot be imported, -these errors are shown when ``verbosity`` is set to ``1`` or higher. +these errors are shown when ``verbosity`` is set to ``1`` or higher. Duplicate +imports are automatically handled. Note that automatic imports can be disabled for a specific ``shell`` session using the :option:`--no-imports ` flag. To permanently diff --git a/tests/shell/tests.py b/tests/shell/tests.py index 49c85ecbe3..ff4db089f7 100644 --- a/tests/shell/tests.py +++ b/tests/shell/tests.py @@ -303,11 +303,16 @@ class ShellCommandAutoImportsTestCase(SimpleTestCase): def test_message_with_stdout_listing_objects_with_isort_not_installed(self): class TestCommand(shell.Command): def get_auto_imports(self): + # Include duplicate import strings to ensure proper handling, + # independent of isort's deduplication (#36252). return super().get_auto_imports() + [ "django.urls.reverse", "django.urls.resolve", "shell", "django", + "django.urls.reverse", + "shell", + "django", ] with captured_stdout() as stdout: