#35429: Add argparse choices to --database options -------------------------------------+------------------------------------- Reporter: Adam | Owner: nobody Johnson | Type: | Status: new Cleanup/optimization | Component: Core | Version: dev (Management commands) | Severity: Normal | Keywords: Triage Stage: | Has patch: 0 Unreviewed | Needs documentation: 0 | Needs tests: 0 Patch needs improvement: 0 | Easy pickings: 1 UI/UX: 0 | -------------------------------------+------------------------------------- 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') }}} -- Ticket URL: <https://code.djangoproject.com/ticket/35429> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/0107018f404fabaf-19430c7f-59ab-4285-8546-0ddf5bbed4e5-000000%40eu-central-1.amazonses.com.