8
9
Applications can register their own actions with ``manage.py``. For example,
9
10
you might want to add a ``manage.py`` action for a Django app that you're
11
distributing. In this document, we will be building a custom ``closepoll``
12
command for the ``polls`` application from the
13
:ref:`tutorial<intro-tutorial01>`.
12
To do this, just add a ``management/commands`` directory to your application.
15
To do this, just add a ``management/commands`` directory to the application.
13
16
Each Python module in that directory will be auto-discovered and registered as
14
17
a command that can be executed as an action when you run ``manage.py``::
26
In this example, the ``explode`` command will be made available to any project
27
that includes the ``blog`` application in ``settings.INSTALLED_APPS``.
29
The ``explode.py`` module has only one requirement -- it must define a class
30
called ``Command`` that extends ``django.core.management.base.BaseCommand``.
32
For more details on how to define your own commands, look at the code for the
33
existing ``django-admin.py`` commands, in ``/django/core/management/commands``.
b'\\ No newline at end of file'
30
In this example, the ``closepoll`` command will be made available to any project
31
that includes the ``polls`` application in :setting:`INSTALLED_APPS`.
33
The ``closepoll.py`` module has only one requirement -- it must define a class
34
``Command`` that extends :class:`BaseCommand` or one of its
35
:ref:`subclasses<ref-basecommand-subclasses>`.
37
.. admonition:: Standalone scripts
39
Custom management commands are especially useful for running standalone
40
scripts or for scripts that are periodically executed from the UNIX crontab
41
or from Windows scheduled tasks control panel.
43
To implement the command, edit ``polls/management/commands/closepoll.py`` to
46
.. code-block:: python
48
from django.core.management.base import BaseCommand, CommandError
49
from example.polls.models import Poll
51
class Command(BaseCommand):
52
args = '<poll_id poll_id ...>'
53
help = 'Closes the specified poll for voting'
55
def handle(self, *args, **options):
58
poll = Poll.objects.get(pk=int(poll_id))
59
except Poll.DoesNotExist:
60
raise CommandError('Poll "%s" does not exist' % poll_id)
65
print 'Successfully closed poll "%s"' % poll_id
67
The new custom command can be called using ``python manage.py closepoll
70
The ``handle()`` method takes zero or more ``poll_ids`` and sets ``poll.opened``
71
to ``False`` for each one. If the user referenced any nonexistant polls, a
72
:class:`CommandError` is raised. The ``poll.opened`` attribute does not exist
73
in the :ref:`tutorial<intro-tutorial01>` and was added to
74
``polls.models.Poll`` for this example.
76
The same ``closepoll`` could be easily modified to delete a given poll instead
77
of closing it by accepting additional command line options. These custom options
78
must be added to :attr:`~BaseCommand.option_list` like this:
80
.. code-block:: python
82
from optparse import make_option
84
class Command(BaseCommand):
85
option_list = BaseCommand.option_list + (
86
make_option('--delete',
90
help='Delete poll instead of closing it'),
94
In addition to being able to add custom command line options, all
95
:ref:`management commands<ref-django-admin>` can accept some
96
default options such as :djadminopt:`--verbosity` and :djadminopt:`--traceback`.
101
.. class:: BaseCommand
103
The base class from which all management commands ultimately derive.
105
Use this class if you want access to all of the mechanisms which
106
parse the command-line arguments and work out what code to call in
107
response; if you don't need to change any of that behavior,
108
consider using one of its :ref:`subclasses<ref-basecommand-subclasses>`.
110
Subclassing the :class:`BaseCommand` class requires that you implement the
111
:meth:`~BaseCommand.handle` method.
116
All attributes can be set in your derived class and can be used in
117
:class:`BaseCommand`'s :ref:`subclasses<ref-basecommand-subclasses>`.
119
.. attribute:: BaseCommand.args
121
A string listing the arguments accepted by the command,
122
suitable for use in help messages; e.g., a command which takes
123
a list of application names might set this to '<appname
126
.. attribute:: BaseCommand.can_import_settings
128
A boolean indicating whether the command needs to be able to
129
import Django settings; if ``True``, ``execute()`` will verify
130
that this is possible before proceeding. Default value is
133
.. attribute:: BaseCommand.help
135
A short description of the command, which will be printed in the
136
help message when the user runs the command
137
``python manage.py help <command>``.
139
.. attribute:: BaseCommand.option_list
141
This is the list of ``optparse`` options which will be fed
142
into the command's ``OptionParser`` for parsing arguments.
144
.. attribute:: BaseCommand.output_transaction
146
A boolean indicating whether the command outputs SQL
147
statements; if ``True``, the output will automatically be
148
wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is
151
.. attribute:: BaseCommand.requires_model_validation
153
A boolean; if ``True``, validation of installed models will be
154
performed prior to executing the command. Default value is
155
``True``. To validate an individual application's models
156
rather than all applications' models, call
157
:meth:`~BaseCommand.validate` from :meth:`~BaseCommand.handle`.
162
:class:`BaseCommand` has a few methods that can be overridden but only
163
the :meth:`~BaseCommand.handle` method must be implemented.
165
.. admonition:: Implementing a constructor in a subclass
167
If you implement ``__init__`` in your subclass of :class:`BaseCommand`,
168
you must call :class:`BaseCommand`'s ``__init__``.
170
.. code-block:: python
172
class Command(BaseCommand):
173
def __init__(self, *args, **kwargs):
174
super(Command, self).__init__(*args, **kwargs)
177
.. method:: BaseCommand.get_version()
179
Return the Django version, which should be correct for all
180
built-in Django commands. User-supplied commands can
181
override this method to return their own version.
183
.. method:: BaseCommand.execute(*args, **options)
185
Try to execute this command, performing model validation if
186
needed (as controlled by the attribute
187
:attr:`requires_model_validation`). If the command raises a
188
:class:`CommandError`, intercept it and print it sensibly to
191
.. method:: BaseCommand.handle(*args, **options)
193
The actual logic of the command. Subclasses must implement this method.
195
.. _ref-basecommand-subclasses:
197
BaseCommand subclasses
198
----------------------
200
.. class:: AppCommand
202
A management command which takes one or more installed application
203
names as arguments, and does something with each of them.
205
Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
206
:meth:`~AppCommand.handle_app`, which will be called once for each application.
208
.. method:: AppCommand.handle_app(app, **options)
210
Perform the command's actions for ``app``, which will be the
211
Python module corresponding to an application name given on
214
.. class:: LabelCommand
216
A management command which takes one or more arbitrary arguments
217
(labels) on the command line, and does something with each of
220
Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
221
:meth:`~LabelCommand.handle_label`, which will be called once for each label.
223
.. method:: LabelCommand.handle_label(label, **options)
225
Perform the command's actions for ``label``, which will be the
226
string as given on the command line.
228
.. class:: NoArgsCommand
230
A command which takes no arguments on the command line.
232
Rather than implementing :meth:`~BaseCommand.handle`, subclasses must implement
233
:meth:`~NoArgsCommand.handle_noargs`; :meth:`~BaseCommand.handle` itself is
234
overridden to ensure no arguments are passed to the command.
236
.. method:: NoArgsCommand.handle_noargs(**options)
238
Perform this command's actions
240
.. _ref-command-exceptions:
245
.. class:: CommandError
247
Exception class indicating a problem while executing a management
250
If this exception is raised during the execution of a management
251
command, it will be caught and turned into a nicely-printed error
252
message to the appropriate output stream (i.e., stderr); as a
253
result, raising this exception (with a sensible description of the
254
error) is the preferred way to indicate that something has gone
255
wrong in the execution of a command.