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.

parse_args(args=None, namespace=None)[source]
error(message: string)[source]

Prints a usage message incorporating the message to stderr and exits.

If you override this in a subclass, it should not return – it should either exit or raise an exception.

add_subparsers(**kwargs)[source]
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'}
add_usage(usage, actions, *args, **kwargs)[source]
add_arguments(actions)[source]
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.

isatty()[source]

Return whether this is an ‘interactive’ stream.

Return False if it can’t be determined.

write(msg='', style_func=None, ending=None)[source]

Write string to stream. Returns the number of characters written (which is always equal to the length of the string).

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:

  1. django-admin or manage.py loads the command class and calls its run_from_argv() method.

  2. The run_from_argv() method calls create_parser() to get an ArgumentParser for the arguments, parses them, performs any environment changes requested by options like pythonpath, and then calls the execute() method, passing the parsed arguments.

  3. The execute() method attempts to carry out the command by calling the handle() method with the parsed arguments; any output produced by handle() will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in BEGIN and COMMIT.

  4. If handle() or execute() raised any exception (e.g. CommandError), run_from_argv() will instead print an error message to stderr.

Thus, the handle() method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in handle(), or perform some additional parsing work in handle() 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 with BEGIN; and COMMIT;. Default value is False.

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) from handle(), where app_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_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

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 raised Exception is not CommandError, 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.

check_migrations()[source]

Print a warning if the set of migrations on disk don’t match the migrations in the database.

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

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

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 implement handle_app_config(), which will be called once for each application.

missing_args_message = 'Enter at least one application label.'
add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

handle(*app_labels, **options)[source]

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

handle_app_config(app_config, **options)[source]

Perform the command’s actions for app_config, an AppConfig instance corresponding to an application label given on the command line.

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 implement handle_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.'
add_arguments(parser)[source]

Entry point for subclassed commands to add custom arguments.

handle(*labels, **options)[source]

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

handle_label(label, **options)[source]

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