- fr
- Language: en
Writing custom django-admin commands¶
Applications can register their own actions with manage.py
. For example,
you might want to add a manage.py
action for a Django app that you’re
distributing. In this document, we will be building a custom closepoll
command for the polls
application from the
tutorial.
To do this, just add a management/commands
directory to the application.
Django will register a manage.py
command for each Python module in that
directory whose name doesn’t begin with an underscore. For example:
polls/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
_private.py
closepoll.py
tests.py
views.py
On Python 2, be sure to include __init__.py
files in both the
management
and management/commands
directories as done above or your
command will not be detected.
In this example, the closepoll
command will be made available to any project
that includes the polls
application in INSTALLED_APPS
.
The _private.py
module will not be available as a management command.
The closepoll.py
module has only one requirement – it must define a class
Command
that extends BaseCommand
or one of its
subclasses.
Standalone scripts
Custom management commands are especially useful for running standalone scripts or for scripts that are periodically executed from the UNIX crontab or from Windows scheduled tasks control panel.
To implement the command, edit polls/management/commands/closepoll.py
to
look like this:
from django.core.management.base import BaseCommand, CommandError
from polls.models import Poll
class Command(BaseCommand):
help = 'Closes the specified poll for voting'
def add_arguments(self, parser):
parser.add_argument('poll_id', nargs='+', type=int)
def handle(self, *args, **options):
for poll_id in options['poll_id']:
try:
poll = Poll.objects.get(pk=poll_id)
except Poll.DoesNotExist:
raise CommandError('Poll "%s" does not exist' % poll_id)
poll.opened = False
poll.save()
self.stdout.write('Successfully closed poll "%s"' % poll_id)
Before Django 1.8, management commands were based on the optparse
module, and positional arguments were passed in *args
while optional
arguments were passed in **options
. Now that management commands use
argparse
for argument parsing, all arguments are passed in
**options
by default, unless you name your positional arguments to
args
(compatibility mode). You are encouraged to exclusively use
**options
for new commands.
Note
When you are using management commands and wish to provide console
output, you should write to self.stdout
and self.stderr
,
instead of printing to stdout
and stderr
directly. By
using these proxies, it becomes much easier to test your custom
command. Note also that you don’t need to end messages with a newline
character, it will be added automatically, unless you specify the ending
parameter:
self.stdout.write("Unterminated line", ending='')
The new custom command can be called using python manage.py closepoll
<poll_id>
.
The handle()
method takes one or more poll_ids
and sets poll.opened
to False
for each one. If the user referenced any nonexistent polls, a
CommandError
is raised. The poll.opened
attribute does not exist
in the tutorial and was added to
polls.models.Poll
for this example.
Accepting optional arguments¶
The same closepoll
could be easily modified to delete a given poll instead
of closing it by accepting additional command line options. These custom
options can be added in the add_arguments()
method like this:
class Command(BaseCommand):
def add_arguments(self, parser):
# Positional arguments
parser.add_argument('poll_id', nargs='+', type=int)
# Named (optional) arguments
parser.add_argument('--delete',
action='store_true',
dest='delete',
default=False,
help='Delete poll instead of closing it')
def handle(self, *args, **options):
# ...
if options['delete']:
poll.delete()
# ...
Previously, only the standard optparse
library was supported and
you would have to extend the command option_list
variable with
optparse.make_option()
.
The option (delete
in our example) is available in the options dict
parameter of the handle method. See the argparse
Python documentation
for more about add_argument
usage.
In addition to being able to add custom command line options, all
management commands can accept some
default options such as --verbosity
and --traceback
.
Management commands and locales¶
By default, the BaseCommand.execute()
method deactivates translations
because some commands shipped with Django perform several tasks (for example,
user-facing content rendering and database population) that require a
project-neutral string language.
In previous versions, Django forced the “en-us” locale instead of deactivating translations.
If, for some reason, your custom management command needs to use a fixed locale,
you should manually activate and deactivate it in your
handle()
method using the functions provided by the I18N
support code:
from django.core.management.base import BaseCommand, CommandError
from django.utils import translation
class Command(BaseCommand):
...
can_import_settings = True
def handle(self, *args, **options):
# Activate a fixed locale, e.g. Russian
translation.activate('ru')
# Or you can activate the LANGUAGE_CODE # chosen in the settings:
from django.conf import settings
translation.activate(settings.LANGUAGE_CODE)
# Your command logic here
...
translation.deactivate()
Another need might be that your command simply should use the locale set in
settings and Django should be kept from deactivating it. You can achieve
it by using the BaseCommand.leave_locale_alone
option.
When working on the scenarios described above though, take into account that system management commands typically have to be very careful about running in non-uniform locales, so you might need to:
- Make sure the
USE_I18N
setting is alwaysTrue
when running the command (this is a good example of the potential problems stemming from a dynamic runtime environment that Django commands avoid offhand by deactivating translations). - Review the code of your command and the code it calls for behavioral differences when locales are changed and evaluate its impact on predictable behavior of your command.
Testing¶
Information on how to test custom management commands can be found in the testing docs.
Command objects¶
The base class from which all management commands ultimately derive.
Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don’t need to change any of that behavior, consider using one of its subclasses.
Subclassing the BaseCommand
class requires that you implement the
handle()
method.
Attributes¶
All attributes can be set in your derived class and can be used in
BaseCommand
’s subclasses.
-
BaseCommand.
args
¶ A string listing the arguments accepted by the command, suitable for use in help messages; e.g., a command which takes a list of application names might set this to ‘<app_label app_label …>’.
Deprecated since version 1.8: This should be done now in the
add_arguments()
method, by calling theparser.add_argument()
method. See theclosepoll
example above.
-
BaseCommand.
can_import_settings
¶ A boolean indicating whether the command needs to be able to import Django settings; if
True
,execute()
will verify that this is possible before proceeding. Default value isTrue
.
-
BaseCommand.
help
¶ A short description of the command, which will be printed in the help message when the user runs the command
python manage.py help <command>
.
-
BaseCommand.
missing_args_message
¶ - New in Django 1.8.
If your command defines mandatory positional arguments, you can customize the message error returned in the case of missing arguments. The default is output by
argparse
(“too few arguments”).
-
BaseCommand.
option_list
¶ This is the list of
optparse
options which will be fed into the command’sOptionParser
for parsing arguments.Deprecated since version 1.8: You should now override the
add_arguments()
method to add custom arguments accepted by your command. See the example above.
-
BaseCommand.
output_transaction
¶ A boolean indicating whether the command outputs SQL statements; if
True
, the output will automatically be wrapped withBEGIN;
andCOMMIT;
. Default value isFalse
.
-
BaseCommand.
requires_system_checks
¶ - New in Django 1.7.
A boolean; if
True
, the entire Django project will be checked for potential problems prior to executing the command. Ifrequires_system_checks
is missing, the value ofrequires_model_validation
is used. If the latter flag is missing as well, the default value (True
) is used. Defining bothrequires_system_checks
andrequires_model_validation
will result in an error.
-
BaseCommand.
requires_model_validation
¶ Deprecated since version 1.7: Replaced by
requires_system_checks
A boolean; if
True
, validation of installed models will be performed prior to executing the command. Default value isTrue
. To validate an individual application’s models rather than all applications’ models, callvalidate()
fromhandle()
.
-
BaseCommand.
leave_locale_alone
¶ A boolean indicating whether the locale set in settings should be preserved during the execution of the command instead of being forcibly set to ‘en-us’.
Default value is
False
.Make sure you know what you are doing if you decide to change the value of this option in your custom command if it creates database content that is locale-sensitive and such content shouldn’t contain any translations (like it happens e.g. with django.contrib.auth permissions) as making the locale differ from the de facto default ‘en-us’ might cause unintended effects. Seethe Management commands and locales section above for further details.
This option can’t be
False
when thecan_import_settings
option is set toFalse
too because attempting to set the locale needs access to settings. This condition will generate aCommandError
.
-
BaseCommand.
style
¶ An instance attribute that helps create colored output when writing to
stdout
orstderr
. For example:self.stdout.write(self.style.NOTICE('...'))
See Syntax coloring to learn how to modify the color palette and to see the available styles (use uppercased versions of the “roles” described in that section).
If you pass the
--no-color
option when running your command, allself.style()
calls will return the original string uncolored.
Methods¶
BaseCommand
has a few methods that can be overridden but only
the handle()
method must be implemented.
Implementing a constructor in a subclass
If you implement __init__
in your subclass of BaseCommand
,
you must call BaseCommand
’s __init__
:
class Command(BaseCommand):
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
# ...
-
BaseCommand.
add_arguments
(parser)[source]¶ - New in Django 1.8.
Entry point to add parser arguments to handle command line arguments passed to the command. Custom commands should override this method to add both positional and optional arguments accepted by the command. Calling
super()
is not needed when directly subclassingBaseCommand
.
-
BaseCommand.
get_version
()[source]¶ Returns the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version.
-
BaseCommand.
execute
(*args, **options)[source]¶ Tries to execute this command, performing system checks if needed (as controlled by the
requires_system_checks
attribute). If the command raises aCommandError
, it’s intercepted and printed to stderr.
Calling a management command in your code
execute()
should not be called directly from your code to execute a
command. Use call_command instead.
-
BaseCommand.
handle
(*args, **options)[source]¶ The actual logic of the command. Subclasses must implement this method.
It may return a Unicode string which will be printed to
stdout
(wrapped byBEGIN;
andCOMMIT;
ifoutput_transaction
isTrue
).
-
BaseCommand.
check
(app_configs=None, tags=None, display_num_errors=False)[source]¶ - New in Django 1.7.
Uses the system check framework to inspect the entire Django project for potential problems. Serious problems are raised as a
CommandError
; warnings are output to stderr; minor notifications are output to stdout.If
app_configs
andtags
are bothNone
, all system checks are performed.tags
can be a list of check tags, likecompatibility
ormodels
.
BaseCommand subclasses¶
-
class
AppCommand
¶
A management command which takes one or more installed application labels as arguments, and does something with each of them.
Rather than implementing handle()
, subclasses must
implement handle_app_config()
, which will be called once for
each application.
-
AppCommand.
handle_app_config
(app_config, **options)¶ Perform the command’s actions for
app_config
, which will be anAppConfig
instance corresponding to an application label given on the command line.
Previously, AppCommand
subclasses had to implement
handle_app(app, **options)
where app
was a models module. The new
API makes it possible to handle applications without a models module. The
fastest way to migrate is as follows:
def handle_app_config(app_config, **options):
if app_config.models_module is None:
return # Or raise an exception.
app = app_config.models_module
# Copy the implementation of handle_app(app_config, **options) here.
However, you may be able to simplify the implementation by using directly
the attributes of app_config
.
-
class
LabelCommand
¶
A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them.
Rather than implementing handle()
, subclasses must implement
handle_label()
, which will be called once for each label.
-
LabelCommand.
handle_label
(label, **options)¶ Perform the command’s actions for
label
, which will be the string as given on the command line.
-
class
NoArgsCommand
¶
Deprecated since version 1.8: Use BaseCommand
instead, which takes no arguments by default.
A command which takes no arguments on the command line.
Rather than implementing handle()
, subclasses must implement
handle_noargs()
; handle()
itself is
overridden to ensure no arguments are passed to the command.
-
NoArgsCommand.
handle_noargs
(**options)¶ Perform this command’s actions
Command exceptions¶
Exception class indicating a problem while executing a management command.
If this exception is raised during the execution of a management command from a command line console, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command.
If a management command is called from code through call_command, it’s up to you to catch the exception when needed.