custom-management-commands.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. On Python 2, be sure to include ``__init__.py`` files in both the
  25. ``management`` and ``management/commands`` directories as done above or your
  26. command will not be detected.
  27. In this example, the ``closepoll`` command will be made available to any project
  28. that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
  29. The ``_private.py`` module will not be available as a management command.
  30. The ``closepoll.py`` module has only one requirement -- it must define a class
  31. ``Command`` that extends :class:`BaseCommand` or one of its
  32. :ref:`subclasses<ref-basecommand-subclasses>`.
  33. .. admonition:: Standalone scripts
  34. Custom management commands are especially useful for running standalone
  35. scripts or for scripts that are periodically executed from the UNIX crontab
  36. or from Windows scheduled tasks control panel.
  37. To implement the command, edit ``polls/management/commands/closepoll.py`` to
  38. look like this::
  39. from django.core.management.base import BaseCommand, CommandError
  40. from polls.models import Poll
  41. class Command(BaseCommand):
  42. help = 'Closes the specified poll for voting'
  43. def add_arguments(self, parser):
  44. parser.add_argument('poll_id', nargs='+', type=int)
  45. def handle(self, *args, **options):
  46. for poll_id in options['poll_id']:
  47. try:
  48. poll = Poll.objects.get(pk=poll_id)
  49. except Poll.DoesNotExist:
  50. raise CommandError('Poll "%s" does not exist' % poll_id)
  51. poll.opened = False
  52. poll.save()
  53. self.stdout.write('Successfully closed poll "%s"' % poll_id)
  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_id>``.
  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. :class:`CommandError` is raised. The ``poll.opened`` attribute does not exist
  69. in the :doc:`tutorial</intro/tutorial01>` and was added to
  70. ``polls.models.Poll`` 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_id', nargs='+', type=int)
  81. # Named (optional) arguments
  82. parser.add_argument('--delete',
  83. action='store_true',
  84. dest='delete',
  85. default=False,
  86. help='Delete poll instead of closing it')
  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
  97. default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`.
  98. .. _management-commands-and-locales:
  99. Management commands and locales
  100. ===============================
  101. By default, the :meth:`BaseCommand.execute` method deactivates translations
  102. because some commands shipped with Django perform several tasks (for example,
  103. user-facing content rendering and database population) that require a
  104. project-neutral string language.
  105. .. versionchanged:: 1.8
  106. In previous versions, Django forced the "en-us" locale instead of
  107. deactivating translations.
  108. If, for some reason, your custom management command needs to use a fixed locale,
  109. you should manually activate and deactivate it in your
  110. :meth:`~BaseCommand.handle` method using the functions provided by the I18N
  111. support code::
  112. from django.core.management.base import BaseCommand, CommandError
  113. from django.utils import translation
  114. class Command(BaseCommand):
  115. ...
  116. can_import_settings = True
  117. def handle(self, *args, **options):
  118. # Activate a fixed locale, e.g. Russian
  119. translation.activate('ru')
  120. # Or you can activate the LANGUAGE_CODE # chosen in the settings:
  121. from django.conf import settings
  122. translation.activate(settings.LANGUAGE_CODE)
  123. # Your command logic here
  124. ...
  125. translation.deactivate()
  126. Another need might be that your command simply should use the locale set in
  127. settings and Django should be kept from deactivating it. You can achieve
  128. it by using the :data:`BaseCommand.leave_locale_alone` option.
  129. When working on the scenarios described above though, take into account that
  130. system management commands typically have to be very careful about running in
  131. non-uniform locales, so you might need to:
  132. * Make sure the :setting:`USE_I18N` setting is always ``True`` when running
  133. the command (this is a good example of the potential problems stemming
  134. from a dynamic runtime environment that Django commands avoid offhand by
  135. deactivating translations).
  136. * Review the code of your command and the code it calls for behavioral
  137. differences when locales are changed and evaluate its impact on
  138. predictable behavior of your command.
  139. Testing
  140. =======
  141. Information on how to test custom management commands can be found in the
  142. :ref:`testing docs <topics-testing-management-commands>`.
  143. Command objects
  144. ===============
  145. .. class:: BaseCommand
  146. The base class from which all management commands ultimately derive.
  147. Use this class if you want access to all of the mechanisms which
  148. parse the command-line arguments and work out what code to call in
  149. response; if you don't need to change any of that behavior,
  150. consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
  151. Subclassing the :class:`BaseCommand` class requires that you implement the
  152. :meth:`~BaseCommand.handle` method.
  153. Attributes
  154. ----------
  155. All attributes can be set in your derived class and can be used in
  156. :class:`BaseCommand`’s :ref:`subclasses<ref-basecommand-subclasses>`.
  157. .. attribute:: BaseCommand.can_import_settings
  158. A boolean indicating whether the command needs to be able to
  159. import Django settings; if ``True``, ``execute()`` will verify
  160. that this is possible before proceeding. Default value is
  161. ``True``.
  162. .. attribute:: BaseCommand.help
  163. A short description of the command, which will be printed in the
  164. help message when the user runs the command
  165. ``python manage.py help <command>``.
  166. .. attribute:: BaseCommand.missing_args_message
  167. .. versionadded:: 1.8
  168. If your command defines mandatory positional arguments, you can customize
  169. the message error returned in the case of missing arguments. The default is
  170. output by :py:mod:`argparse` ("too few arguments").
  171. .. attribute:: BaseCommand.output_transaction
  172. A boolean indicating whether the command outputs SQL statements; if
  173. ``True``, the output will automatically be wrapped with ``BEGIN;`` and
  174. ``COMMIT;``. Default value is ``False``.
  175. .. attribute:: BaseCommand.requires_system_checks
  176. A boolean; if ``True``, the entire Django project will be checked for
  177. potential problems prior to executing the command. Default value is ``True``.
  178. .. attribute:: BaseCommand.leave_locale_alone
  179. A boolean indicating whether the locale set in settings should be preserved
  180. during the execution of the command instead of being forcibly set to 'en-us'.
  181. Default value is ``False``.
  182. Make sure you know what you are doing if you decide to change the value of
  183. this option in your custom command if it creates database content that
  184. is locale-sensitive and such content shouldn't contain any translations
  185. (like it happens e.g. with django.contrib.auth permissions) as making the
  186. locale differ from the de facto default 'en-us' might cause unintended
  187. effects. Seethe `Management commands and locales`_ section above for
  188. further details.
  189. This option can't be ``False`` when the
  190. :data:`~BaseCommand.can_import_settings` option is set to ``False`` too
  191. because attempting to set the locale needs access to settings. This
  192. condition will generate a :class:`CommandError`.
  193. Methods
  194. -------
  195. :class:`BaseCommand` has a few methods that can be overridden but only
  196. the :meth:`~BaseCommand.handle` method must be implemented.
  197. .. admonition:: Implementing a constructor in a subclass
  198. If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
  199. you must call :class:`BaseCommand`’s ``__init__``::
  200. class Command(BaseCommand):
  201. def __init__(self, *args, **kwargs):
  202. super(Command, self).__init__(*args, **kwargs)
  203. # ...
  204. .. method:: BaseCommand.add_arguments(parser)
  205. .. versionadded:: 1.8
  206. Entry point to add parser arguments to handle command line arguments passed
  207. to the command. Custom commands should override this method to add both
  208. positional and optional arguments accepted by the command. Calling
  209. ``super()`` is not needed when directly subclassing ``BaseCommand``.
  210. .. method:: BaseCommand.get_version()
  211. Returns the Django version, which should be correct for all built-in Django
  212. commands. User-supplied commands can override this method to return their
  213. own version.
  214. .. method:: BaseCommand.execute(*args, **options)
  215. Tries to execute this command, performing system checks if needed (as
  216. controlled by the :attr:`requires_system_checks` attribute). If the command
  217. raises a :class:`CommandError`, it's intercepted and printed to stderr.
  218. .. admonition:: Calling a management command in your code
  219. ``execute()`` should not be called directly from your code to execute a
  220. command. Use :ref:`call_command <call-command>` instead.
  221. .. method:: BaseCommand.handle(*args, **options)
  222. The actual logic of the command. Subclasses must implement this method.
  223. .. method:: BaseCommand.check(app_configs=None, tags=None, display_num_errors=False)
  224. Uses the system check framework to inspect the entire Django project for
  225. potential problems. Serious problems are raised as a :class:`CommandError`;
  226. warnings are output to stderr; minor notifications are output to stdout.
  227. If ``app_configs`` and ``tags`` are both ``None``, all system checks are
  228. performed. ``tags`` can be a list of check tags, like ``compatibility`` or
  229. ``models``.
  230. .. _ref-basecommand-subclasses:
  231. BaseCommand subclasses
  232. ----------------------
  233. .. class:: AppCommand
  234. A management command which takes one or more installed application labels as
  235. arguments, and does something with each of them.
  236. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must
  237. implement :meth:`~AppCommand.handle_app_config`, which will be called once for
  238. each application.
  239. .. method:: AppCommand.handle_app_config(app_config, **options)
  240. Perform the command's actions for ``app_config``, which will be an
  241. :class:`~django.apps.AppConfig` instance corresponding to an application
  242. label given on the command line.
  243. .. class:: LabelCommand
  244. A management command which takes one or more arbitrary arguments (labels) on
  245. the command line, and does something with each of them.
  246. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  247. :meth:`~LabelCommand.handle_label`, which will be called once for each label.
  248. .. method:: LabelCommand.handle_label(label, **options)
  249. Perform the command's actions for ``label``, which will be the string as
  250. given on the command line.
  251. .. class:: NoArgsCommand
  252. .. deprecated:: 1.8
  253. Use :class:`BaseCommand` instead, which takes no arguments by default.
  254. A command which takes no arguments on the command line.
  255. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  256. :meth:`~NoArgsCommand.handle_noargs`; :meth:`~BaseCommand.handle` itself is
  257. overridden to ensure no arguments are passed to the command.
  258. .. method:: NoArgsCommand.handle_noargs(**options)
  259. Perform this command's actions
  260. .. _ref-command-exceptions:
  261. Command exceptions
  262. ------------------
  263. .. class:: CommandError
  264. Exception class indicating a problem while executing a management command.
  265. If this exception is raised during the execution of a management command from a
  266. command line console, it will be caught and turned into a nicely-printed error
  267. message to the appropriate output stream (i.e., stderr); as a result, raising
  268. this exception (with a sensible description of the error) is the preferred way
  269. to indicate that something has gone wrong in the execution of a command.
  270. If a management command is called from code through :ref:`call_command
  271. <call-command>`, it's up to you to catch the exception when needed.