custom-shell.txt 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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 subclasses
  9. ``django.core.management.commands.shell.Command`` and overrides the existing
  10. ``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_namespace()`` method. For example:
  18. .. code-block:: python
  19. :caption: ``polls/management/commands/shell.py``
  20. from django.core.management.commands import shell
  21. class Command(shell.Command):
  22. def get_namespace(self):
  23. from django.urls.base import resolve, reverse
  24. return {
  25. **super().get_namespace(),
  26. "resolve": resolve,
  27. "reverse": reverse,
  28. }
  29. The above customization adds :func:`~django.urls.resolve` and
  30. :func:`~django.urls.reverse` to the default namespace, which includes all
  31. models from all apps. These two functions will then be available when the
  32. shell opens, without a manual import statement.
  33. If you prefer to not have models automatically imported, create a custom
  34. ``get_namespace()`` that excludes the ``super().get_namespace()`` call:
  35. .. code-block:: python
  36. :caption: ``polls/management/commands/shell.py``
  37. from django.core.management.commands import shell
  38. class Command(shell.Command):
  39. def get_namespace(self):
  40. return {}