﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
35429	Add argparse choices to --database options	Adam Johnson	Jae Hyuck Sa 	"Many management commands take a `--database` option to select which database to operate on. Currently, this is unvalidated, causing crashes when a bad name is typed:

{{{
$ ./manage.py migrate --database deflaut
Traceback (most recent call last):
  ...
  File ""/.../django/core/management/commands/migrate.py"", line 100, in handle
    self.check(databases=[database])
  ...
  File ""/.../django/db/models/fields/__init__.py"", line 442, in _check_backend_specific_checks
    errors.extend(connections[alias].validation.check_field(self, **kwargs))
                  ~~~~~~~~~~~^^^^^^^
  File ""/.../django/utils/connection.py"", line 61, in __getitem__
    raise self.exception_class(f""The connection '{alias}' doesn't exist."")
django.utils.connection.ConnectionDoesNotExist: The connection 'deflaut' doesn't exist.
}}}

We can add [https://docs.python.org/3.12/library/argparse.html#choices argparse’s choices] for validation:

{{{
--- django/core/management/commands/migrate.py
+++ django/core/management/commands/migrate.py
@@ -47,6 +47,7 @@ def add_arguments(self, parser):
         parser.add_argument(
             ""--database"",
             default=DEFAULT_DB_ALIAS,
+            choices=tuple(connections),
             help=(
                 'Nominates a database to synchronize. Defaults to the ""default"" '
                 ""database.""
}}}

The failure is then graceful, and lists the available options:

{{{
$ ./manage.py migrate --database deflaut
usage: manage.py migrate ...
manage.py migrate: error: argument --database: invalid choice: 'deflaut' (choose from 'default')
}}}"	Cleanup/optimization	closed	Core (Management commands)	dev	Normal	fixed		Mariusz Felisiak Rishav	Ready for checkin	1	0	0	0	1	0
