custom-management-commands.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. .. code-block:: python
  37. from django.core.management.base import BaseCommand, CommandError
  38. from polls.models import Poll
  39. class Command(BaseCommand):
  40. help = 'Closes the specified poll for voting'
  41. def add_arguments(self, parser):
  42. parser.add_argument('poll_id', nargs='+', type=int)
  43. def handle(self, *args, **options):
  44. for poll_id in options['poll_id']:
  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('Successfully closed poll "%s"' % poll_id)
  52. Before Django 1.8, management commands were based on the :py:mod:`optparse`
  53. module, and positional arguments were passed in ``*args`` while optional
  54. arguments were passed in ``**options``. Now that management commands use
  55. :py:mod:`argparse` for argument parsing, all arguments are passed in
  56. ``**options`` by default, unless you name your positional arguments to ``args``
  57. (compatibility mode). You are encouraged to exclusively use ``**options`` for
  58. new commands.
  59. .. _management-commands-output:
  60. .. note::
  61. When you are using management commands and wish to provide console
  62. output, you should write to ``self.stdout`` and ``self.stderr``,
  63. instead of printing to ``stdout`` and ``stderr`` directly. By
  64. using these proxies, it becomes much easier to test your custom
  65. command. Note also that you don't need to end messages with a newline
  66. character, it will be added automatically, unless you specify the ``ending``
  67. parameter::
  68. self.stdout.write("Unterminated line", ending='')
  69. The new custom command can be called using ``python manage.py closepoll
  70. <poll_id>``.
  71. The ``handle()`` method takes one or more ``poll_ids`` and sets ``poll.opened``
  72. to ``False`` for each one. If the user referenced any nonexistent polls, a
  73. :class:`CommandError` is raised. The ``poll.opened`` attribute does not exist
  74. in the :doc:`tutorial</intro/tutorial01>` and was added to
  75. ``polls.models.Poll`` for this example.
  76. .. _custom-commands-options:
  77. Accepting optional arguments
  78. ============================
  79. The same ``closepoll`` could be easily modified to delete a given poll instead
  80. of closing it by accepting additional command line options. These custom
  81. options can be added in the :meth:`~BaseCommand.add_arguments` method like this:
  82. .. code-block:: python
  83. class Command(BaseCommand):
  84. def add_arguments(self, parser):
  85. # Positional arguments
  86. parser.add_argument('poll_id', nargs='+', type=int)
  87. # Named (optional) arguments
  88. parser.add_argument('--delete',
  89. action='store_true',
  90. dest='delete',
  91. default=False,
  92. help='Delete poll instead of closing it')
  93. def handle(self, *args, **options):
  94. # ...
  95. if options['delete']:
  96. poll.delete()
  97. # ...
  98. .. versionchanged:: 1.8
  99. Previously, only the standard :py:mod:`optparse` library was supported and
  100. you would have to extend the command ``option_list`` variable with
  101. ``optparse.make_option()``.
  102. The option (``delete`` in our example) is available in the options dict
  103. parameter of the handle method. See the :py:mod:`argparse` Python documentation
  104. for more about ``add_argument`` usage.
  105. In addition to being able to add custom command line options, all
  106. :doc:`management commands</ref/django-admin>` can accept some
  107. default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`.
  108. .. _management-commands-and-locales:
  109. Management commands and locales
  110. ===============================
  111. By default, the :meth:`BaseCommand.execute` method sets the hardcoded 'en-us'
  112. locale because some commands shipped with Django perform several tasks
  113. (for example, user-facing content rendering and database population) that
  114. require a system-neutral string language (for which we use 'en-us').
  115. If, for some reason, your custom management command needs to use a fixed locale
  116. different from 'en-us', you should manually activate and deactivate it in your
  117. :meth:`~BaseCommand.handle` or :meth:`~NoArgsCommand.handle_noargs` method using
  118. the functions provided by the I18N support code:
  119. .. code-block:: python
  120. from django.core.management.base import BaseCommand, CommandError
  121. from django.utils import translation
  122. class Command(BaseCommand):
  123. ...
  124. can_import_settings = True
  125. def handle(self, *args, **options):
  126. # Activate a fixed locale, e.g. Russian
  127. translation.activate('ru')
  128. # Or you can activate the LANGUAGE_CODE # chosen in the settings:
  129. #
  130. #from django.conf import settings
  131. #translation.activate(settings.LANGUAGE_CODE)
  132. # Your command logic here
  133. # ...
  134. translation.deactivate()
  135. Another need might be that your command simply should use the locale set in
  136. settings and Django should be kept from forcing it to 'en-us'. You can achieve
  137. it by using the :data:`BaseCommand.leave_locale_alone` option.
  138. When working on the scenarios described above though, take into account that
  139. system management commands typically have to be very careful about running in
  140. non-uniform locales, so you might need to:
  141. * Make sure the :setting:`USE_I18N` setting is always ``True`` when running
  142. the command (this is a good example of the potential problems stemming
  143. from a dynamic runtime environment that Django commands avoid offhand by
  144. always using a fixed locale).
  145. * Review the code of your command and the code it calls for behavioral
  146. differences when locales are changed and evaluate its impact on
  147. predictable behavior of your command.
  148. Command objects
  149. ===============
  150. .. class:: BaseCommand
  151. The base class from which all management commands ultimately derive.
  152. Use this class if you want access to all of the mechanisms which
  153. parse the command-line arguments and work out what code to call in
  154. response; if you don't need to change any of that behavior,
  155. consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
  156. Subclassing the :class:`BaseCommand` class requires that you implement the
  157. :meth:`~BaseCommand.handle` method.
  158. Attributes
  159. ----------
  160. All attributes can be set in your derived class and can be used in
  161. :class:`BaseCommand`’s :ref:`subclasses<ref-basecommand-subclasses>`.
  162. .. attribute:: BaseCommand.args
  163. A string listing the arguments accepted by the command,
  164. suitable for use in help messages; e.g., a command which takes
  165. a list of application names might set this to '<app_label
  166. app_label ...>'.
  167. .. deprecated:: 1.8
  168. This should be done now in the :meth:`~BaseCommand.add_arguments()`
  169. method, by calling the ``parser.add_argument()`` method. See the
  170. ``closepoll`` example above.
  171. .. attribute:: BaseCommand.can_import_settings
  172. A boolean indicating whether the command needs to be able to
  173. import Django settings; if ``True``, ``execute()`` will verify
  174. that this is possible before proceeding. Default value is
  175. ``True``.
  176. .. attribute:: BaseCommand.help
  177. A short description of the command, which will be printed in the
  178. help message when the user runs the command
  179. ``python manage.py help <command>``.
  180. .. attribute:: BaseCommand.missing_args_message
  181. .. versionadded:: 1.8
  182. If your command defines mandatory positional arguments, you can customize
  183. the message error returned in the case of missing arguments. The default is
  184. output by :py:mod:`argparse` ("too few arguments").
  185. .. attribute:: BaseCommand.option_list
  186. This is the list of ``optparse`` options which will be fed
  187. into the command's ``OptionParser`` for parsing arguments.
  188. .. deprecated:: 1.8
  189. You should now override the :meth:`~BaseCommand.add_arguments` method to
  190. add custom arguments accepted by your command.
  191. See :ref:`the example above <custom-commands-options>`.
  192. .. attribute:: BaseCommand.output_transaction
  193. A boolean indicating whether the command outputs SQL
  194. statements; if ``True``, the output will automatically be
  195. wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
  196. ``False``.
  197. .. attribute:: BaseCommand.requires_system_checks
  198. .. versionadded:: 1.7
  199. A boolean; if ``True``, the entire Django project will be checked for
  200. potential problems prior to executing the command. If
  201. ``requires_system_checks`` is missing, the value of
  202. ``requires_model_validation`` is used. If the latter flag is missing
  203. as well, the default value (``True``) is used. Defining both
  204. ``requires_system_checks`` and ``requires_model_validation`` will result
  205. in an error.
  206. .. attribute:: BaseCommand.requires_model_validation
  207. .. deprecated:: 1.7
  208. Replaced by ``requires_system_checks``
  209. A boolean; if ``True``, validation of installed models will be
  210. performed prior to executing the command. Default value is
  211. ``True``. To validate an individual application's models
  212. rather than all applications' models, call
  213. :meth:`~BaseCommand.validate` from :meth:`~BaseCommand.handle`.
  214. .. attribute:: BaseCommand.leave_locale_alone
  215. A boolean indicating whether the locale set in settings should be preserved
  216. during the execution of the command instead of being forcibly set to 'en-us'.
  217. Default value is ``False``.
  218. Make sure you know what you are doing if you decide to change the value of
  219. this option in your custom command if it creates database content that
  220. is locale-sensitive and such content shouldn't contain any translations (like
  221. it happens e.g. with django.contrib.auth permissions) as making the locale
  222. differ from the de facto default 'en-us' might cause unintended effects. See
  223. the `Management commands and locales`_ section above for further details.
  224. This option can't be ``False`` when the
  225. :data:`~BaseCommand.can_import_settings` option is set to ``False`` too
  226. because attempting to set the locale needs access to settings. This condition
  227. will generate a :class:`CommandError`.
  228. Methods
  229. -------
  230. :class:`BaseCommand` has a few methods that can be overridden but only
  231. the :meth:`~BaseCommand.handle` method must be implemented.
  232. .. admonition:: Implementing a constructor in a subclass
  233. If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
  234. you must call :class:`BaseCommand`’s ``__init__``.
  235. .. code-block:: python
  236. class Command(BaseCommand):
  237. def __init__(self, *args, **kwargs):
  238. super(Command, self).__init__(*args, **kwargs)
  239. # ...
  240. .. method:: BaseCommand.add_arguments(parser)
  241. .. versionadded:: 1.8
  242. Entry point to add parser arguments to handle command line arguments passed
  243. to the command. Custom commands should override this method to add both
  244. positional and optional arguments accepted by the command. Calling
  245. ``super()`` is not needed when directly subclassing ``BaseCommand``.
  246. .. method:: BaseCommand.get_version()
  247. Return the Django version, which should be correct for all
  248. built-in Django commands. User-supplied commands can
  249. override this method to return their own version.
  250. .. method:: BaseCommand.execute(*args, **options)
  251. Try to execute this command, performing model validation if
  252. needed (as controlled by the attribute
  253. :attr:`requires_model_validation`). If the command raises a
  254. :class:`CommandError`, intercept it and print it sensibly to
  255. stderr.
  256. .. admonition:: Calling a management command in your code
  257. ``execute()`` should not be called directly from your code to execute a
  258. command. Use :ref:`call_command <call-command>` instead.
  259. .. method:: BaseCommand.handle(*args, **options)
  260. The actual logic of the command. Subclasses must implement this method.
  261. .. method:: BaseCommand.check(app_configs=None, tags=None, display_num_errors=False)
  262. .. versionadded:: 1.7
  263. Uses the system check framework to inspect the entire Django project for
  264. potential problems. Serious problems are raised as a :class:`CommandError`;
  265. warnings are output to stderr; minor notifications are output to stdout.
  266. If ``apps`` and ``tags`` are both None, all system checks are performed.
  267. ``tags`` can be a list of check tags, like ``compatibility`` or ``models``.
  268. .. method:: BaseCommand.validate(app=None, display_num_errors=False)
  269. .. deprecated:: 1.7
  270. Replaced with the :djadmin:`check` command
  271. If ``app`` is None, then all installed apps are checked for errors.
  272. .. _ref-basecommand-subclasses:
  273. BaseCommand subclasses
  274. ----------------------
  275. .. class:: AppCommand
  276. A management command which takes one or more installed application labels as
  277. arguments, and does something with each of them.
  278. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must
  279. implement :meth:`~AppCommand.handle_app_config`, which will be called once for
  280. each application.
  281. .. method:: AppCommand.handle_app_config(app_config, **options)
  282. Perform the command's actions for ``app_config``, which will be an
  283. :class:`~django.apps.AppConfig` instance corresponding to an application
  284. label given on the command line.
  285. .. versionchanged:: 1.7
  286. Previously, :class:`AppCommand` subclasses had to implement
  287. ``handle_app(app, **options)`` where ``app`` was a models module. The new
  288. API makes it possible to handle applications without a models module. The
  289. fastest way to migrate is as follows::
  290. def handle_app_config(app_config, **options):
  291. if app_config.models_module is None:
  292. return # Or raise an exception.
  293. app = app_config.models_module
  294. # Copy the implementation of handle_app(app_config, **options) here.
  295. However, you may be able to simplify the implementation by using directly
  296. the attributes of ``app_config``.
  297. .. class:: LabelCommand
  298. A management command which takes one or more arbitrary arguments
  299. (labels) on the command line, and does something with each of
  300. them.
  301. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  302. :meth:`~LabelCommand.handle_label`, which will be called once for each label.
  303. .. method:: LabelCommand.handle_label(label, **options)
  304. Perform the command's actions for ``label``, which will be the
  305. string as given on the command line.
  306. .. class:: NoArgsCommand
  307. A command which takes no arguments on the command line.
  308. Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
  309. :meth:`~NoArgsCommand.handle_noargs`; :meth:`~BaseCommand.handle` itself is
  310. overridden to ensure no arguments are passed to the command.
  311. .. method:: NoArgsCommand.handle_noargs(**options)
  312. Perform this command's actions
  313. .. _ref-command-exceptions:
  314. Command exceptions
  315. ------------------
  316. .. class:: CommandError
  317. Exception class indicating a problem while executing a management
  318. command.
  319. If this exception is raised during the execution of a management
  320. command from a command line console, it will be caught and turned into a
  321. nicely-printed error message to the appropriate output stream (i.e., stderr);
  322. as a result, raising this exception (with a sensible description of the
  323. error) is the preferred way to indicate that something has gone
  324. wrong in the execution of a command.
  325. If a management command is called from code through
  326. :ref:`call_command <call-command>`, it's up to you to catch the exception
  327. when needed.