Debian Codegraph @

docs/howto/custom-management-commands.txt

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