custom-management-commands.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. ==============================================
  2. How to create custom ``django-admin`` commands
  3. ==============================================
  4. .. module:: django.core.management
  5. Applications can register their own actions with ``manage.py``. For example,
  6. you might want to add a ``manage.py`` action for a Django app that you're
  7. distributing. In this document, we will be building a custom ``closepoll``
  8. command for the ``polls`` application from the
  9. :doc:`tutorial</intro/tutorial01>`.
  10. To do this, add a ``management/commands`` directory to the application. Django
  11. will register a ``manage.py`` command for each Python module in that directory
  12. whose name doesn't begin with an underscore. For example:
  13. .. code-block:: text
  14. polls/
  15. __init__.py
  16. models.py
  17. management/
  18. __init__.py
  19. commands/
  20. __init__.py
  21. _private.py
  22. closepoll.py
  23. tests.py
  24. views.py
  25. In this example, the ``closepoll`` command will be made available to any project
  26. that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
  27. The ``_private.py`` module will not be available as a management command.
  28. The ``closepoll.py`` module has only one requirement -- it must define a class
  29. ``Command`` that extends :class:`BaseCommand` or one of its
  30. :ref:`subclasses<ref-basecommand-subclasses>`.
  31. .. admonition:: Standalone scripts
  32. Custom management commands are especially useful for running standalone
  33. scripts or for scripts that are periodically executed from the UNIX crontab
  34. or from Windows scheduled tasks control panel.
  35. To implement the command, edit ``polls/management/commands/closepoll.py`` to
  36. look like this::
  37. from django.core.management.base import BaseCommand, CommandError
  38. from polls.models import Question as Poll
  39. class Command(BaseCommand):
  40. help = "Closes the specified poll for voting"
  41. def add_arguments(self, parser):
  42. parser.add_argument("poll_ids", nargs="+", type=int)
  43. def handle(self, *args, **options):
  44. for poll_id in options["poll_ids"]:
  45. try:
  46. poll = Poll.objects.get(pk=poll_id)
  47. except Poll.DoesNotExist:
  48. raise CommandError('Poll "%s" does not exist' % poll_id)
  49. poll.opened = False
  50. poll.save()
  51. self.stdout.write(
  52. self.style.SUCCESS('Successfully closed poll "%s"' % poll_id)
  53. )
  54. .. _management-commands-output:
  55. .. note::
  56. When you are using management commands and wish to provide console
  57. output, you should write to ``self.stdout`` and ``self.stderr``,
  58. instead of printing to ``stdout`` and ``stderr`` directly. By
  59. using these proxies, it becomes much easier to test your custom
  60. command. Note also that you don't need to end messages with a newline
  61. character, it will be added automatically, unless you specify the ``ending``
  62. parameter::
  63. self.stdout.write("Unterminated line", ending="")
  64. The new custom command can be called using ``python manage.py closepoll
  65. <poll_ids>``.
  66. The ``handle()`` method takes one or more ``poll_ids`` and sets ``poll.opened``
  67. to ``False`` for each one. If the user referenced any nonexistent polls, a
  68. :exc:`CommandError` is raised. The ``poll.opened`` attribute does not exist in
  69. the :doc:`tutorial</intro/tutorial02>` and was added to
  70. ``polls.models.Question`` for this example.
  71. .. _custom-commands-options:
  72. Accepting optional arguments
  73. ============================
  74. The same ``closepoll`` could be easily modified to delete a given poll instead
  75. of closing it by accepting additional command line options. These custom
  76. options can be added in the :meth:`~BaseCommand.add_arguments` method like this::
  77. class Command(BaseCommand):
  78. def add_arguments(self, parser):
  79. # Positional arguments
  80. parser.add_argument("poll_ids", nargs="+", type=int)
  81. # Named (optional) arguments
  82. parser.add_argument(
  83. "--delete",
  84. action="store_true",
  85. help="Delete poll instead of closing it",
  86. )
  87. def handle(self, *args, **options):
  88. # ...
  89. if options["delete"]:
  90. poll.delete()
  91. # ...
  92. The option (``delete`` in our example) is available in the options dict
  93. parameter of the handle method. See the :py:mod:`argparse` Python documentation
  94. for more about ``add_argument`` usage.
  95. In addition to being able to add custom command line options, all
  96. :doc:`management commands</ref/django-admin>` can accept some default options
  97. such as :option:`--verbosity` and :option:`--traceback`.
  98. .. _management-commands-and-locales:
  99. Management commands and locales
  100. ===============================
  101. By default, management commands are executed with the current active locale.
  102. If, for some reason, your custom management command must run without an active
  103. locale (for example, to prevent translated content from being inserted into
  104. the database), deactivate translations using the ``@no_translations``
  105. decorator on your :meth:`~BaseCommand.handle` method::
  106. from django.core.management.base import BaseCommand, no_translations
  107. class Command(BaseCommand):
  108. ...
  109. @no_translations
  110. def handle(self, *args, **options): ...
  111. Since translation deactivation requires access to configured settings, the
  112. decorator can't be used for commands that work without configured settings.
  113. Testing
  114. =======
  115. Information on how to test custom management commands can be found in the
  116. :ref:`testing docs <topics-testing-management-commands>`.
  117. Overriding commands
  118. ===================
  119. Django registers the built-in commands and then searches for commands in
  120. :setting:`INSTALLED_APPS` in reverse. During the search, if a command name
  121. duplicates an already registered command, the newly discovered command
  122. overrides the first.
  123. In other words, to override a command, the new command must have the same name
  124. and its app must be before the overridden command's app in
  125. :setting:`INSTALLED_APPS`.
  126. Management commands from third-party apps that have been unintentionally
  127. overridden can be made available under a new name by creating a new command in
  128. one of your project's apps (ordered before the third-party app in
  129. :setting:`INSTALLED_APPS`) which imports the ``Command`` of the overridden
  130. command.
  131. Command objects
  132. ===============
  133. .. class:: BaseCommand
  134. The base class from which all management commands ultimately derive.
  135. Use this class if you want access to all of the mechanisms which
  136. parse the command-line arguments and work out what code to call in
  137. response; if you don't need to change any of that behavior,
  138. consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
  139. Subclassing the :class:`BaseCommand` class requires that you implement the
  140. :meth:`~BaseCommand.handle` method.
  141. Attributes
  142. ----------
  143. All attributes can be set in your derived class and can be used in
  144. :class:`BaseCommand`’s :ref:`subclasses<ref-basecommand-subclasses>`.
  145. .. attribute:: BaseCommand.help
  146. A short description of the command, which will be printed in the
  147. help message when the user runs the command
  148. ``python manage.py help <command>``.
  149. .. attribute:: BaseCommand.missing_args_message
  150. If your command defines mandatory positional arguments, you can customize
  151. the message error returned in the case of missing arguments. The default is
  152. output by :py:mod:`argparse` ("too few arguments").
  153. .. attribute:: BaseCommand.output_transaction
  154. A boolean indicating whether the command outputs SQL statements; if
  155. ``True``, the output will automatically be wrapped with ``BEGIN;`` and
  156. ``COMMIT;``. Default value is ``False``.
  157. .. attribute:: BaseCommand.requires_migrations_checks
  158. A boolean; if ``True``, the command prints a warning if the set of
  159. migrations on disk don't match the migrations in the database. A warning
  160. doesn't prevent the command from executing. Default value is ``False``.
  161. .. attribute:: BaseCommand.requires_system_checks
  162. A list or tuple of tags, e.g. ``[Tags.staticfiles, Tags.models]``. System
  163. checks :ref:`registered in the chosen tags <registering-labeling-checks>`
  164. will be checked for errors prior to executing the command. The value
  165. ``'__all__'`` can be used to specify that all system checks should be
  166. performed. Default value is ``'__all__'``.
  167. .. attribute:: BaseCommand.style
  168. An instance attribute that helps create colored output when writing to
  169. ``stdout`` or ``stderr``. For example::
  170. self.stdout.write(self.style.SUCCESS("..."))
  171. See :ref:`syntax-coloring` to learn how to modify the color palette and to
  172. see the available styles (use uppercased versions of the "roles" described
  173. in that section).
  174. If you pass the :option:`--no-color` option when running your command, all
  175. ``self.style()`` calls will return the original string uncolored.
  176. .. attribute:: BaseCommand.suppressed_base_arguments
  177. The default command options to suppress in the help output. This should be
  178. a set of option names (e.g. ``'--verbosity'``). The default values for the
  179. suppressed options are still passed.
  180. Methods
  181. -------
  182. :class:`BaseCommand` has a few methods that can be overridden but only
  183. the :meth:`~BaseCommand.handle` method must be implemented.
  184. .. admonition:: Implementing a constructor in a subclass
  185. If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
  186. you must call :class:`BaseCommand`’s ``__init__``::
  187. class Command(BaseCommand):
  188. def __init__(self, *args, **kwargs):
  189. super().__init__(*args, **kwargs)
  190. # ...
  191. .. method:: BaseCommand.create_parser(prog_name, subcommand, **kwargs)
  192. Returns a ``CommandParser`` instance, which is an
  193. :class:`~argparse.ArgumentParser` subclass with a few customizations for
  194. Django.
  195. You can customize the instance by overriding this method and calling
  196. ``super()`` with ``kwargs`` of :class:`~argparse.ArgumentParser` parameters.
  197. .. method:: BaseCommand.add_arguments(parser)
  198. Entry point to add parser arguments to handle command line arguments passed
  199. to the command. Custom commands should override this method to add both
  200. positional and optional arguments accepted by the command. Calling
  201. ``super()`` is not needed when directly subclassing ``BaseCommand``.
  202. .. method:: BaseCommand.get_version()
  203. Returns the Django version, which should be correct for all built-in Django
  204. commands. User-supplied commands can override this method to return their
  205. own version.
  206. .. method:: BaseCommand.execute(*args, **options)
  207. Tries to execute this command, performing system checks if needed (as
  208. controlled by the :attr:`requires_system_checks` attribute). If the command
  209. raises a :exc:`CommandError`, it's intercepted and printed to ``stderr``.
  210. .. admonition:: Calling a management command in your code
  211. ``execute()`` should not be called directly from your code to execute a
  212. command. Use :func:`~django.core.management.call_command` instead.
  213. .. method:: BaseCommand.handle(*args, **options)
  214. The actual logic of the command. Subclasses must implement this method.
  215. It may return a string which will be printed to ``stdout`` (wrapped
  216. by ``BEGIN;`` and ``COMMIT;`` if :attr:`output_transaction` is ``True``).
  217. .. method:: BaseCommand.check(app_configs=None, tags=None,display_num_errors=False, include_deployment_checks=False, fail_level=checks.ERROR, databases=None)
  218. Uses the system check framework to inspect the entire Django project for
  219. potential problems. Serious problems are raised as a :exc:`CommandError`;
  220. warnings are output to ``stderr``; minor notifications are output to
  221. ``stdout``.
  222. If ``app_configs`` and ``tags`` are both ``None``, all system checks are
  223. performed except deployment and database related checks. ``tags`` can be a
  224. list of check tags, like ``compatibility`` or ``models``.
  225. You can pass ``include_deployment_checks=True`` to also perform deployment
  226. checks, and list of database aliases in the ``databases`` to run database
  227. related checks against them.
  228. .. _ref-basecommand-subclasses:
  229. ``BaseCommand`` subclasses
  230. --------------------------
  231. .. class:: AppCommand
  232. A management command which takes one or more installed application labels as
  233. arguments, and does something with each of them.
  234. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must
  235. implement :meth:`~AppCommand.handle_app_config`, which will be called once for
  236. each application.
  237. .. method:: AppCommand.handle_app_config(app_config, **options)
  238. Perform the command's actions for ``app_config``, which will be an
  239. :class:`~django.apps.AppConfig` instance corresponding to an application
  240. label given on the command line.
  241. .. class:: LabelCommand
  242. A management command which takes one or more arbitrary arguments (labels) on
  243. the command line, and does something with each of them.
  244. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  245. :meth:`~LabelCommand.handle_label`, which will be called once for each label.
  246. .. attribute:: LabelCommand.label
  247. A string describing the arbitrary arguments passed to the command. The
  248. string is used in the usage text and error messages of the command.
  249. Defaults to ``'label'``.
  250. .. method:: LabelCommand.handle_label(label, **options)
  251. Perform the command's actions for ``label``, which will be the string as
  252. given on the command line.
  253. Command exceptions
  254. ------------------
  255. .. exception:: CommandError(returncode=1)
  256. Exception class indicating a problem while executing a management command.
  257. If this exception is raised during the execution of a management command from a
  258. command line console, it will be caught and turned into a nicely-printed error
  259. message to the appropriate output stream (i.e., ``stderr``); as a result,
  260. raising this exception (with a sensible description of the error) is the
  261. preferred way to indicate that something has gone wrong in the execution of a
  262. command. It accepts the optional ``returncode`` argument to customize the exit
  263. status for the management command to exit with, using :func:`sys.exit`.
  264. If a management command is called from code through
  265. :func:`~django.core.management.call_command`, it's up to you to catch the
  266. exception when needed.