custom-shell.txt 2.5 KB

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