'Best practice for defining default app settings for custom django module?

Is there a defined best practice for defining custom settings that come with a django app.

What I have at the moment is a separate file called app_settings.py that looks like this:

from django.conf import settings

# MY_SETTING_1 is required and will brake the application if not defined
try:
    MY_SETTING_1 = str(getattr(settings, 'MY_SETTING_1'))
except AttributeError:
    raise ImproperlyConfigured ('MY_SETTING_1 not defined in settings.py.')


# MY_SETTING_2 is not required and has a default value
MY_SETTING_2 = getattr(settings, 'MY_SETTING_2', ['default_value'])

Then I am importing this in my views.py, and using it like this:

from my_app import app_settings

print (app_settings.MY_SETTING_1)
print (app_settings.MY_SETTING_2)

This works ok, but I am not quite happy with the design. I am assuming that I can somehow use the class defined in apps.py, but I am not sure how.

Is there a best (or better) practice for this?



Solution 1:[1]

You could try https://pypi.org/project/typed_app_settings/.

Example:

# my_app/app_settings.py
from typed_app_settings import UndefinedValue, typed_app_settings_dict

@typed_app_settings_dict("MY_APP")
class Settings:
    MY_SETTING_1: str = UndefinedValue()
    MY_SETTING_2: str = "default_value"

settings = Settings()

Then in the view you would just use it like this.

from my_app.app_settings import settings

print(app_settings.MY_SETTING_1)
print(app_settings.MY_SETTING_2)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 KebdnK