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. Each Python module in that directory will be auto-discovered and registered as a command that can be executed as an action when you run manage.py:
polls/
__init__.py
models.py
management/
__init__.py
commands/
__init__.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.
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 example.polls.models import Poll
class Command(BaseCommand):
args = '<poll_id poll_id ...>'
help = 'Closes the specified poll for voting'
def handle(self, *args, **options):
for poll_id in args:
try:
poll = Poll.objects.get(pk=int(poll_id))
except Poll.DoesNotExist:
raise CommandError('Poll "%s" does not exist' % poll_id)
poll.opened = False
poll.save()
print 'Successfully closed poll "%s"' % poll_id
The new custom command can be called using python manage.py closepoll <poll_id>.
The handle() method takes zero or more poll_ids and sets poll.opened to False for each one. If the user referenced any nonexistant 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.
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 must be added to option_list like this:
from optparse import make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--delete',
action='store_true',
dest='delete',
default=False,
help='Delete poll instead of closing it'),
)
# ...
In addition to being able to add custom command line options, all management commands can accept some default options such as --verbosity and --traceback.
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.
All attributes can be set in your derived class and can be used in BaseCommand's subclasses.
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)
# ...
A management command which takes one or more installed application names as arguments, and does something with each of them.
Rather than implementing handle(), subclasses must implement handle_app(), which will be called once for each application.
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.
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.
Exception class indicating a problem while executing a management command.
If this exception is raised during the execution of a management command, 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.
Jul 05, 2010