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’redistributing. In this document, we will be building a custom closepollcommand for the polls application from thetutorial.

To do this, add a management/commands directory to the application. Djangowill register a manage.py command for each Python module in that directorywhose name doesn’t begin with an underscore. For example:

  1. polls/
  2. __init__.py
  3. models.py
  4. management/
  5. commands/
  6. _private.py
  7. closepoll.py
  8. tests.py
  9. views.py

In this example, the closepoll command will be made available to any projectthat 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 classCommand that extends BaseCommand or one of itssubclasses.

Standalone scripts

Custom management commands are especially useful for running standalonescripts or for scripts that are periodically executed from the UNIX crontabor from Windows scheduled tasks control panel.

To implement the command, edit polls/management/commands/closepoll.py tolook like this:

  1. from django.core.management.base import BaseCommand, CommandError
  2. from polls.models import Question as Poll
  3.  
  4. class Command(BaseCommand):
  5. help = 'Closes the specified poll for voting'
  6.  
  7. def add_arguments(self, parser):
  8. parser.add_argument('poll_ids', nargs='+', type=int)
  9.  
  10. def handle(self, *args, **options):
  11. for poll_id in options['poll_ids']:
  12. try:
  13. poll = Poll.objects.get(pk=poll_id)
  14. except Poll.DoesNotExist:
  15. raise CommandError('Poll "%s" does not exist' % poll_id)
  16.  
  17. poll.opened = False
  18. poll.save()
  19.  
  20. self.stdout.write(self.style.SUCCESS('Successfully closed poll "%s"' % poll_id))

Note

When you are using management commands and wish to provide consoleoutput, you should write to self.stdout and self.stderr,instead of printing to stdout and stderr directly. Byusing these proxies, it becomes much easier to test your customcommand. Note also that you don’t need to end messages with a newlinecharacter, it will be added automatically, unless you specify the endingparameter:

  1. self.stdout.write("Unterminated line", ending='')

The new custom command can be called using python manage.py closepoll<poll_ids>.

The handle() method takes one or more poll_ids and sets poll.openedto False for each one. If the user referenced any nonexistent polls, aCommandError is raised. The poll.opened attribute does not exist inthe tutorial and was added topolls.models.Question for this example.

Accepting optional arguments

The same closepoll could be easily modified to delete a given poll insteadof closing it by accepting additional command line options. These customoptions can be added in the add_arguments() method like this:

  1. class Command(BaseCommand):
  2. def add_arguments(self, parser):
  3. # Positional arguments
  4. parser.add_argument('poll_ids', nargs='+', type=int)
  5.  
  6. # Named (optional) arguments
  7. parser.add_argument(
  8. '--delete',
  9. action='store_true',
  10. help='Delete poll instead of closing it',
  11. )
  12.  
  13. def handle(self, *args, **options):
  14. # ...
  15. if options['delete']:
  16. poll.delete()
  17. # ...

The option (delete in our example) is available in the options dictparameter of the handle method. See the argparse Python documentationfor more about add_argument usage.

In addition to being able to add custom command line options, allmanagement commands can accept some default optionssuch as —verbosity and —traceback.

Management commands and locales

By default, management commands are executed with the current active locale.

If, for some reason, your custom management command must run without an activelocale (for example, to prevent translated content from being inserted intothe database), deactivate translations using the @no_translationsdecorator on your handle() method:

  1. from django.core.management.base import BaseCommand, no_translations
  2.  
  3. class Command(BaseCommand):
  4. ...
  5.  
  6. @no_translations
  7. def handle(self, *args, **options):
  8. ...

Since translation deactivation requires access to configured settings, thedecorator can’t be used for commands that work without configured settings.

Testing

Information on how to test custom management commands can be found in thetesting docs.

Overriding commands

Django registers the built-in commands and then searches for commands inINSTALLED_APPS in reverse. During the search, if a command nameduplicates an already registered command, the newly discovered commandoverrides the first.

In other words, to override a command, the new command must have the same nameand its app must be before the overridden command’s app inINSTALLED_APPS.

Management commands from third-party apps that have been unintentionallyoverridden can be made available under a new name by creating a new command inone of your project’s apps (ordered before the third-party app inINSTALLED_APPS) which imports the Command of the overriddencommand.

Command objects

  • class BaseCommand
  • The base class from which all management commands ultimately derive.

Use this class if you want access to all of the mechanisms whichparse the command-line arguments and work out what code to call inresponse; 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 thehandle() method.

Attributes

All attributes can be set in your derived class and can be used inBaseCommand’s subclasses.

  • BaseCommand.help
  • A short description of the command, which will be printed in thehelp message when the user runs the commandpython manage.py help <command>.

  • BaseCommand.missing_args_message

  • If your command defines mandatory positional arguments, you can customizethe message error returned in the case of missing arguments. The default isoutput by argparse (“too few arguments”).

  • BaseCommand.output_transaction

  • A boolean indicating whether the command outputs SQL statements; ifTrue, the output will automatically be wrapped with BEGIN; andCOMMIT;. Default value is False.

  • BaseCommand.requires_migrations_checks

  • A boolean; if True, the command prints a warning if the set ofmigrations on disk don’t match the migrations in the database. A warningdoesn’t prevent the command from executing. Default value is False.

  • BaseCommand.requires_system_checks

  • A boolean; if True, the entire Django project will be checked forpotential problems prior to executing the command. Default value is True.

  • BaseCommand.style

  • An instance attribute that helps create colored output when writing tostdout or stderr. For example:
  1. self.stdout.write(self.style.SUCCESS('...'))

See Syntax coloring to learn how to modify the color palette and tosee the available styles (use uppercased versions of the “roles” describedin 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 onlythe 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:

  1. class Command(BaseCommand):
  2. def __init__(self, *args, **kwargs):
  3. super().__init__(*args, **kwargs)
  4. # ...
  • BaseCommand.createparser(_prog_name, subcommand, **kwargs)
  • Returns a CommandParser instance, which is anArgumentParser subclass with a few customizations forDjango.

You can customize the instance by overriding this method and callingsuper() with kwargs of ArgumentParser parameters.

Changed in Django 2.2:kwargs was added.

  • BaseCommand.addarguments(_parser)
  • Entry point to add parser arguments to handle command line arguments passedto the command. Custom commands should override this method to add bothpositional and optional arguments accepted by the command. Callingsuper() is not needed when directly subclassing BaseCommand.

  • BaseCommand.get_version()

  • Returns the Django version, which should be correct for all built-in Djangocommands. User-supplied commands can override this method to return theirown version.

  • BaseCommand.execute(*args, **options)

  • Tries to execute this command, performing system checks if needed (ascontrolled by the requires_system_checks attribute). If the commandraises a CommandError, 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 acommand. Use call_command() instead.

  • BaseCommand.handle(*args, **options)
  • The actual logic of the command. Subclasses must implement this method.

It may return a string which will be printed to stdout (wrappedby BEGIN; and COMMIT; if output_transaction is True).

  • BaseCommand.check(app_configs=None, tags=None, display_num_errors=False)
  • Uses the system check framework to inspect the entire Django project forpotential problems. Serious problems are raised as a CommandError;warnings are output to stderr; minor notifications are output to stdout.

If app_configs and tags are both None, all system checks areperformed. tags can be a list of check tags, like compatibility ormodels.

BaseCommand subclasses

  • class AppCommand
  • A management command which takes one or more installed application labels asarguments, and does something with each of them.

Rather than implementing handle(), subclasses mustimplement handle_app_config(), which will be called once foreach application.

  • AppCommand.handleapp_config(_app_config, **options)
  • Perform the command’s actions for app_config, which will be anAppConfig instance corresponding to an applicationlabel given on the command line.

  • class LabelCommand

  • A management command which takes one or more arbitrary arguments (labels) onthe command line, and does something with each of them.

Rather than implementing handle(), subclasses must implementhandle_label(), which will be called once for each label.

  • LabelCommand.label
  • A string describing the arbitrary arguments passed to the command. Thestring is used in the usage text and error messages of the command.Defaults to 'label'.

  • LabelCommand.handlelabel(_label, **options)

  • Perform the command’s actions for label, which will be the string asgiven on the command line.

Command exceptions

  • exception CommandError
  • Exception class indicating a problem while executing a management command.

If this exception is raised during the execution of a management command from acommand line console, it will be caught and turned into a nicely-printed errormessage to the appropriate output stream (i.e., stderr); as a result, raisingthis exception (with a sensible description of the error) is the preferred wayto indicate that something has gone wrong in the execution of a command.

If a management command is called from code throughcall_command(), it’s up to you to catch theexception when needed.