Use this snippet at the end of your main settings.py file to automagically import the settings defined in each app of INSTALLED_APPS
that begins with APPS_BASE_NAME
.
Set APPS_BASE_NAME
to the base name of your Django project (e.g. the parent directory) and put settings.py
files in every app directory (next to the models.py
file) you want to have local settings in.
# works in the Django shell
>>> from django.conf import settings
>>> settings.TEST_SETTING_FROM_APP
"this is great for reusable apps"
Please keep in mind that the imported settings will overwrite the already given and preceding settings, e.g. when you use the same setting name in different applications.
Props to bartTC for the idea.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | # [...]
# this is an example!
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
# my apps:
'myapps.blog',
'myapps.chat',
'myapps.forum',
)
APPS_BASE_NAME = 'myapps'
# Import Applicaton-specific Settings
for app in INSTALLED_APPS:
if app.startswith(APPS_BASE_NAME):
try:
app_module = __import__(app, globals(), locals(), ["settings"])
app_settings = getattr(app_module, "settings", None)
for setting in dir(app_settings):
if setting == setting.upper():
locals()[setting] = getattr(app_settings, setting)
except ImportError:
pass
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Isn't it a better approach to set the default values in the app and overwrite them in the main settings.py when necessary? For example:
blog/model.py
#
Please login first before commenting.