Best way to avoid hard-coding Django defaults when using external configs?

Hi everyone! :wave:

I load settings from an external TOML file. My goal is to pull in a setting like SESSION_COOKIE_SAMESITE and use the default Django value if it’s not defined in the config.

Here’s a simplified version of what I have so far:

import tomllib
from django.conf import global_settings

CONFIG_PATH = BASE_DIR / "config.toml"
CONFIG = tomllib.load(CONFIG_PATH.open(mode="rb"))

SESSION_COOKIE_SAMESITE = CONFIG.get( "SESSION_COOKIE_SAMESITE", global_settings.SESSION_COOKIE_SAMESITE)

I know the docs mention that importing global_settings is redundant, but I don’t see another straightforward way to avoid hard-coding Django’s defaults. Hard-coding feels risky since future Django upgrades might change default values.

For example, without global_settings, I would need to do this:

SESSION_COOKIE_SAMESITE = CONFIG.get("SESSION_COOKIE_SAMESITE", "Lax")

But hard-coding "Lax" here makes the code fragile — if Django changes the default value in the future, I’d have to manually update it.

I’ve also tried conditional assignment patterns or defining the value elsewhere in the settings module, but I couldn’t get it to work in a clean way.

So, my question is:
Does anyone have a recommended pattern or best practice for referencing the default Django settings without hard-coding values or importing global_settings?

<opinion>
For this purpose, I don’t see an issue regarding the import of global_settings. You’re not importing it simply to set those values.
</opinion>

The alternatives I can think of would be to either conditionally set the setting if it is set in the file, or to iterate through all settings in the file and set everything that is loaded from the file having a key of all capital letters.

You could also create a settings utility:

from django.conf import global_settings

def get_setting(config: dict, key: str) -> Any:
    """Get setting from config or fall back to Django default."""
    return config.get(key, getattr(global_settings, key))

SESSION_COOKIE_SAMESITE = get_setting(CONFIG, "SESSION_COOKIE_SAMESITE")
  • config: Your TOML configuration dictionary
  • key: The name of the setting you want to get

The diffsettings management command could also help to find settings which unintentionally deviate from the defaults: