django.core.management.base
Base classes for writing management commands (named commands which can
be executed through django-admin
or manage.py
).
- exception django.core.management.base.CommandError(*args, returncode=1, **kwargs)[source]
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.
- exception django.core.management.base.SystemCheckError(*args, returncode=1, **kwargs)[source]
The system check framework detected unrecoverable errors.
- class django.core.management.base.CommandParser(*, missing_args_message=None, called_from_command_line=None, **kwargs)[source]
Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically.
- django.core.management.base.handle_default_options(options)[source]
Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands.
- django.core.management.base.no_translations(handle_func)[source]
Decorator that forces a command to run with translations deactivated.
- class django.core.management.base.DjangoHelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)[source]
Customized formatter so that command-specific arguments appear in the –help output before arguments common to all commands.
- show_last = {'--force-color', '--no-color', '--pythonpath', '--settings', '--skip-checks', '--traceback', '--verbosity', '--version'}
- class django.core.management.base.OutputWrapper(out, ending='\n')[source]
Wrapper around stdout/stderr
- property style_func
- flush()[source]
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- class django.core.management.base.BaseCommand(stdout=None, stderr=None, no_color=False, force_color=False)[source]
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 the subclasses defined in this file.
If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows:
django-admin
ormanage.py
loads the command class and calls itsrun_from_argv()
method.The
run_from_argv()
method callscreate_parser()
to get anArgumentParser
for the arguments, parses them, performs any environment changes requested by options likepythonpath
, and then calls theexecute()
method, passing the parsed arguments.The
execute()
method attempts to carry out the command by calling thehandle()
method with the parsed arguments; any output produced byhandle()
will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped inBEGIN
andCOMMIT
.If
handle()
orexecute()
raised any exception (e.g.CommandError
),run_from_argv()
will instead print an error message tostderr
.
Thus, the
handle()
method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic inhandle()
, or perform some additional parsing work inhandle()
and then delegate from it to more specialized methods as needed.Several attributes affect behavior at various steps along the way:
help
A short description of the command, which will be printed in help messages.
output_transaction
A boolean indicating whether the command outputs SQL statements; if
True
, the output will automatically be wrapped withBEGIN;
andCOMMIT;
. Default value isFalse
.requires_migrations_checks
A boolean; if
True
, the command prints a warning if the set of migrations on disk don’t match the migrations in the database.requires_system_checks
A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value ‘__all__’ can be used to specify that all system checks should be performed. Default value is ‘__all__’.
To validate an individual application’s models rather than all applications’ models, call
self.check(app_configs)
fromhandle()
, whereapp_configs
is the list of application’s configuration provided by the app registry.stealth_options
A tuple of any options the command uses which aren’t defined by the argument parser.
- help = ''
- output_transaction = False
- requires_migrations_checks = False
- requires_system_checks = '__all__'
- base_stealth_options = ('stderr', 'stdout')
- stealth_options = ()
- suppressed_base_arguments = {}
- get_version()[source]
Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version.
- create_parser(prog_name, subcommand, **kwargs)[source]
Create and return the
ArgumentParser
which will be used to parse the arguments to this command.
- add_base_argument(parser, *args, **kwargs)[source]
Call the parser’s add_argument() method, suppressing the help text according to BaseCommand.suppressed_base_arguments.
- print_help(prog_name, subcommand)[source]
Print the help message for this command, derived from
self.usage()
.
- run_from_argv(argv)[source]
Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a
CommandError
, intercept it and print it sensibly to stderr. If the--traceback
option is present or the raisedException
is notCommandError
, raise it.
- execute(*args, **options)[source]
Try to execute this command, performing system checks if needed (as controlled by the
requires_system_checks
attribute, except if force-skipped).
- check(app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False, fail_level=40, databases=None)[source]
Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don’t raise an exception.
- class django.core.management.base.AppCommand(stdout=None, stderr=None, no_color=False, force_color=False)[source]
A management command which takes one or more installed application labels as arguments, and does something with each of them.
Rather than implementing
handle()
, subclasses must implementhandle_app_config()
, which will be called once for each application.- missing_args_message = 'Enter at least one application label.'
- class django.core.management.base.LabelCommand(stdout=None, stderr=None, no_color=False, force_color=False)[source]
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 implementhandle_label()
, which will be called once for each label.If the arguments should be names of installed applications, use
AppCommand
instead.- label = 'label'
- missing_args_message = 'Enter at least one label.'