Movatterモバイル変換


[0]ホーム

URL:


Skip to main content
Django

The web framework for perfectionists with deadlines.

Documentation

How to create customdjango-admin commands

Applications can register their own actions withmanage.py. For example,you might want to add amanage.py action for a Django app that you’redistributing. In this document, we will be building a customclosepollcommand for thepolls application from thetutorial.

To do this, add amanagement/commands directory to the application. Djangowill register amanage.py command for each Python module in that directorywhose 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

In this example, theclosepoll command will be made available to any projectthat includes thepolls application inINSTALLED_APPS.

The_private.py module will not be available as a management command.

Theclosepoll.py module has only one requirement – it must define a classCommand that extendsBaseCommand 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, editpolls/management/commands/closepoll.py tolook like this:

fromdjango.core.management.baseimportBaseCommand,CommandErrorfrompolls.modelsimportQuestionasPollclassCommand(BaseCommand):help="Closes the specified poll for voting"defadd_arguments(self,parser):parser.add_argument("poll_ids",nargs="+",type=int)defhandle(self,*args,**options):forpoll_idinoptions["poll_ids"]:try:poll=Poll.objects.get(pk=poll_id)exceptPoll.DoesNotExist:raiseCommandError('Poll "%s" does not exist'%poll_id)poll.opened=Falsepoll.save()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 toself.stdout andself.stderr,instead of printing tostdout andstderr 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 theendingparameter:

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

The new custom command can be called usingpythonmanage.pyclosepoll<poll_ids>.

Thehandle() method takes one or morepoll_ids and setspoll.openedtoFalse for each one. If the user referenced any nonexistent polls, aCommandError is raised. Thepoll.opened attribute does not exist inthetutorial and was added topolls.models.Question for this example.

Accepting optional arguments

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

classCommand(BaseCommand):defadd_arguments(self,parser):# Positional argumentsparser.add_argument("poll_ids",nargs="+",type=int)# Named (optional) argumentsparser.add_argument("--delete",action="store_true",help="Delete poll instead of closing it",)defhandle(self,*args,**options):# ...ifoptions["delete"]:poll.delete()# ...

The option (delete in our example) is available in the options dictparameter of the handle method. See theargparse Python documentationfor more aboutadd_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 yourhandle() method:

fromdjango.core.management.baseimportBaseCommand,no_translationsclassCommand(BaseCommand):...@no_translationsdefhandle(self,*args,**options):...

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 theCommand of the overriddencommand.

Command objects

classBaseCommand[source]

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 itssubclasses.

Subclassing theBaseCommand class requires that you implement thehandle() method.

Attributes

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

BaseCommand.help

A short description of the command, which will be printed in thehelp message when the user runs the commandpythonmanage.pyhelp<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 byargparse (“too few arguments”).

BaseCommand.output_transaction

A boolean indicating whether the command outputs SQL statements; ifTrue, the output will automatically be wrapped withBEGIN; andCOMMIT;. Default value isFalse.

BaseCommand.requires_migrations_checks

A boolean; ifTrue, 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 isFalse.

BaseCommand.requires_system_checks

A list or tuple of tags, e.g.[Tags.staticfiles,Tags.models]. Systemchecksregistered in the chosen tagswill be checked for errors prior to executing the command. The value'__all__' can be used to specify that all system checks should beperformed. Default value is'__all__'.

BaseCommand.style

An instance attribute that helps create colored output when writing tostdout orstderr. For example:

self.stdout.write(self.style.SUCCESS("..."))

SeeSyntax 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.

BaseCommand.suppressed_base_arguments

The default command options to suppress in the help output. This should bea set of option names (e.g.'--verbosity'). The default values for thesuppressed options are still passed.

Methods

BaseCommand has a few methods that can be overridden but onlythehandle() method must be implemented.

Implementing a constructor in a subclass

If you implement__init__ in your subclass ofBaseCommand,you must callBaseCommand’s__init__:

classCommand(BaseCommand):def__init__(self,*args,**kwargs):super().__init__(*args,**kwargs)# ...
BaseCommand.create_parser(prog_name,subcommand,**kwargs)[source]

Returns aCommandParser instance, which is anArgumentParser subclass with a few customizations forDjango.

You can customize the instance by overriding this method and callingsuper() withkwargs ofArgumentParser parameters.

BaseCommand.add_arguments(parser)[source]

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 subclassingBaseCommand.

BaseCommand.get_version()[source]

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)[source]

Tries to execute this command, performing system checks if needed (ascontrolled by therequires_system_checks attribute). If the commandraises aCommandError, it’s intercepted and printed tostderr.

Calling a management command in your code

execute() should not be called directly from your code to execute acommand. Usecall_command() instead.

BaseCommand.handle(*args,**options)[source]

The actual logic of the command. Subclasses must implement this method.

It may return a string which will be printed tostdout (wrappedbyBEGIN; andCOMMIT; ifoutput_transaction isTrue).

BaseCommand.check(app_configs=None,tags=None,display_num_errors=False,include_deployment_checks=False,fail_level=checks.ERROR,databases=None)[source]

Uses the system check framework to inspect the entire Django project forpotential problems. Serious problems are raised as aCommandError;warnings are output tostderr; minor notifications are output tostdout.

Ifapp_configs andtags are bothNone, all system checks areperformed except deployment and database related checks.tags can be alist of check tags, likecompatibility ormodels.

You can passinclude_deployment_checks=True to also perform deploymentchecks, and list of database aliases in thedatabases to run databaserelated checks against them.

BaseCommand subclasses

classAppCommand

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

Rather than implementinghandle(), subclasses mustimplementhandle_app_config(), which will be called once foreach application.

AppCommand.handle_app_config(app_config,**options)

Perform the command’s actions forapp_config, which will be anAppConfig instance corresponding to an applicationlabel given on the command line.

classLabelCommand

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

Rather than implementinghandle(), 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.handle_label(label,**options)

Perform the command’s actions forlabel, which will be the string asgiven on the command line.

Command exceptions

exceptionCommandError(returncode=1)[source]

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,raising this exception (with a sensible description of the error) is thepreferred way to indicate that something has gone wrong in the execution of acommand. It accepts the optionalreturncode argument to customize the exitstatus for the management command to exit with, usingsys.exit().

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

Back to Top

Additional Information

Support Django!

Support Django!

Contents

Getting help

FAQ
Try the FAQ — it's got answers to many common questions.
Index,Module Index, orTable of Contents
Handy when looking for specific information.
Django Discord Server
Join the Django Discord Community.
Official Django Forum
Join the community on the Django Forum.
Ticket tracker
Report bugs with Django or Django documentation in our ticket tracker.

Download:

Offline (Django 5.0):HTML |PDF |ePub
Provided byRead the Docs.

Diamond and Platinum Members

Sentry
JetBrains
This document is for an insecure version of Django that is no longer supported. Please upgrade to a newer release!

[8]ページ先頭

©2009-2025 Movatter.jp