Debian Codegraph @

docs/howto/custom-shell.txt

raw
1 ======================================
2 How to customize the ``shell`` command
3 ======================================
4
5 The Django :djadmin:`shell` is an interactive Python environment that provides
6 access to models and settings, making it useful for testing code, experimenting
7 with queries, and interacting with application data.
8
9 Customizing the :djadmin:`shell` command allows adding extra functionality or
10 pre-loading specific modules. To do this, create a new management command that
11 subclasses ``django.core.management.commands.shell.Command`` and overrides the
12 existing ``shell`` management command. For more details, refer to the guide on
13 :ref:`overriding commands <overriding-commands>`.
14
15 .. _customizing-shell-auto-imports:
16
17 Customize automatic imports
18 ===========================
19
20 .. versionadded:: 5.2
21
22 To customize the automatic import behavior of the :djadmin:`shell` management
23 command, override the ``get_auto_imports()`` method. This method should return
24 a sequence of import paths for objects or modules available in the application.
25 For example:
26
27 .. code-block:: python
28 :caption: ``polls/management/commands/shell.py``
29
30 from django.core.management.commands import shell
31
32
33 class Command(shell.Command):
34 def get_auto_imports(self):
35 return super().get_auto_imports() + [
36 "django.urls.reverse",
37 "django.urls.resolve",
38 ]
39
40 The customization above adds :func:`~django.urls.resolve` and
41 :func:`~django.urls.reverse` to the default namespace, which already includes
42 all models from the apps listed in :setting:`INSTALLED_APPS`. These objects
43 will be available in the ``shell`` without requiring a manual import.
44
45 Running this customized ``shell`` command with ``verbosity=2`` would show:
46
47 .. console::
48
49 8 objects imported automatically:
50
51 from django.contrib.admin.models import LogEntry
52 from django.contrib.auth.models import Group, Permission, User
53 from django.contrib.contenttypes.models import ContentType
54 from django.contrib.sessions.models import Session
55 from django.urls import resolve, reverse
56
57 If an overridden ``shell`` command includes paths that cannot be imported,
58 these errors are shown when ``verbosity`` is set to ``1`` or higher. Duplicate
59 imports are automatically handled.
60
61 Note that automatic imports can be disabled for a specific ``shell`` session
62 using the :option:`--no-imports <shell --no-imports>` flag. To permanently
63 disable automatic imports, override ``get_auto_imports()`` to return ``None``::
64
65 class Command(shell.Command):
66 def get_auto_imports(self):
67 return None