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/ commands/ _private.py closepoll.py tests.py views.py
In this example, the
closepoll command will be made available to any project that includes the
polls application in INSTALLED_APPS.
_private.py module will not be available as a management command.
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 Question as Poll class Command(BaseCommand): help = 'Closes the specified poll for voting' def add_arguments(self, parser): parser.add_argument('poll_ids', nargs='+', type=int) def handle(self, *args, **options): for poll_id in options['poll_ids']: 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(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))
When you are using management commands and wish to provide console output, you should write to
self.stderr, instead of printing to
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
self.stdout.write("Unterminated line", ending='')
The new custom command can be called using
python manage.py closepoll .
handle() method takes one or more
poll_ids and sets
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.Question for this example.
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_ids', nargs='+', type=int) # Named (optional) arguments parser.add_argument( '--delete', action='store_true', help='Delete poll instead of closing it', ) def handle(self, *args, **options): # ... if options['delete']: poll.delete() # ...
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
By default, management commands are executed with the current active locale.
If, for some reason, your custom management command must run without an active locale (for example, to prevent translated content from being inserted into the database), deactivate translations using the
@no_translations decorator on your handle() method:
from django.core.management.base import BaseCommand, no_translations class Command(BaseCommand): ... @no_translations def handle(self, *args, **options): ...
Since translation deactivation requires access to configured settings, the decorator can’t be used for commands that work without configured settings.
@no_translations decorator is new. In older versions, translations are deactivated before running a command unless the command’s
leave_locale_alone attribute (now removed) is set to
Information on how to test custom management commands can be found in the testing docs.
Django registers the built-in commands and then searches for commands in INSTALLED_APPS in reverse. During the search, if a command name duplicates an already registered command, the newly discovered command overrides the first.
In other words, to override a command, the new command must have the same name and its app must be before the overridden command’s app in INSTALLED_APPS.
Management commands from third-party apps that have been unintentionally overridden can be made available under a new name by creating a new command in one of your project’s apps (ordered before the third-party app in INSTALLED_APPS) which imports the
Command of the overridden command.
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.
python manage.py help.
True, the output will automatically be wrapped with
COMMIT;. Default value is
True, the command prints a warning if the set of migrations on disk don’t match the migrations in the database. A warning doesn’t prevent the command from executing. Default value is
True, the entire Django project will be checked for potential problems prior to executing the command. Default value is
An instance attribute that helps create colored output when writing to
stderr. For example:
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, all
self.style() calls will return the original string uncolored.
Implementing a constructor in a subclass
class Command(BaseCommand): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ...
CommandParser instance, which is an ArgumentParser subclass with a few customizations for Django.
You can customize the instance by overriding this method and calling
kwargs of ArgumentParser parameters.
kwargs was added.
super()is not needed when directly subclassing
Calling a management command in your code
execute() should not be called directly from your code to execute a command. Use call_command() instead.
The actual logic of the command. Subclasses must implement this method.
It may return a string which will be printed to
stdout (wrapped by
COMMIT; if output_transaction is
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.
tags are both
None, all system checks are performed.
tags can be a list of check tags, like
A management command which takes one or more installed application labels as arguments, and does something with each of them.
app_config, which will be an AppConfig instance corresponding to an application label given on the command line.
A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them.
label, which will be the string as given on the command line.
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.