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