custom-management-commands.txt 15 KB

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