How should django packages handle default settings?

I just ran into an issue where I was trying to override a package’s settings in testing, only to realize it wasn’t working because of the way the package sets and uses settings.

The package follows the common pattern of configuring settings by importing the global settings to get defaults, e.g. in myapp/settings.py

from django.conf import settings

MYAPP_MODE = getattr(settings, "MYAPP_MODE", "prod")

and then in the package code just imports those settings:

import .settings as app_settings

if app_settings.MYAPP_MODE:
    ...

Because the global settings are only imported at startup, standard ways of overriding settings during testing don’t work - you have to to import the app’s settings module and override things there.

Is there a better/recommended way of doing this?

follow this: Configuring Django Settings: Best Practices.

Thanks, I think that’s all good advice for end-users of Django and Django packages. I guess what I’m asking here is more about developers of 3rd party packages, and how to implement settings for their package that:

  • Have default values if the user doesn’t specify them, and
  • Are overrideable by the end-user at runtime, and during testing

One way to find answers here would be to look at some third-party packages to see how they handle it.

Handling the defaults is easy. As you pointed out above, you can do something like:

from django.conf import settings
a_setting = getattr(settings, 'MY_SETTING', default_value)

But do this where it’s needed, not in a particular apps’ settings file.

You can look through any number of other packages to get some more ideas.