#37574 assigned Bug

Management commands with requires_settings = False crash when DJANGO_SETTINGS_MODULE's package is missing

Reported by: Konstantinos Giannopoulos Owned by: Konstantinos Giannopoulos
Component: Core (Management commands) Version: dev
Severity: Release blocker Keywords: requires_settings DJANGO_SETTINGS_MODULE
Cc: Konstantinos Giannopoulos Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

#32915 (537c6df3e6) added BaseCommand.requires_settings, new in 6.2. The docs say: "if False, any ImportError from a missing settings module is suppressed". startproject, startapp, shell and makemessages set it to False.

This doesn't work when DJANGO_SETTINGS_MODULE names a module inside a package that doesn't exist, which is the usual "mysite.settings" form:

$ DJANGO_SETTINGS_MODULE=nosuchpkg.settings django-admin startproject demo
Traceback (most recent call last):
  ...
ModuleNotFoundError: No module named 'nosuchpkg'

No project is created. A stale DJANGO_SETTINGS_MODULE exported in the shell from another project is enough to trigger it. With a top-level name the same command works:

$ DJANGO_SETTINGS_MODULE=nosuchsettings django-admin startproject demo2
$ ls -d demo2
demo2

Before 537c6df3e6, the dotted form worked too: startproject created the project, and django-admin version printed the version (now it crashes the same way).

Cause: requires_settings = False only suppresses ImproperlyConfigured. ManagementUtility.execute() stores it in settings_exception, and fetch_command() ignores it for these commands. 537c6df3e6 removed the "except ImportError" from execute(), and made Settings.init() convert the ImportError into ImproperlyConfigured only when exc.name == self.SETTINGS_MODULE. When the package is missing, exc.name is the package ("nosuchpkg"), not "nosuchpkg.settings", so the ModuleNotFoundError escapes execute() before the command is even looked up. The tests from #32915 only use top-level module names (bad_settings, fake_settings_module), so they don't cover this case.

Suggested fix: also treat it as a missing settings module when exc.name is one of the settings module's parent packages:

if exc.name and f"{self.SETTINGS_MODULE}.".startswith(f"{exc.name}."):

The ImproperlyConfigured is then suppressed for requires_settings = False commands as documented. An ImportError raised inside a settings module that does exist (e.g. it imports a missing dependency) is still re-raised, as #32915 intended. I have regression tests for settings_tests and admin_scripts. They fail on main and pass with this change, and I can open a PR if the ticket is accepted.

Change History (0)

Note: See TracTickets for help on using tickets.
Back to Top