custom-management-commands.txt 13 KB

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