The Django documentation mentions that you can add your own settings to django.conf.settings
. So if my project's settings.py
defines
APPLES = 1
I can access that with settings.APPLES
in my apps in that project.
But if my settings.py
doesn't define that value, accessing settings.APPLES
obviously won't work. Is there some way to define a default value for APPLES
that is used if there is no explicit setting in settings.py
?
I'd like best to define the default value in the module/package that requires the setting.
I recently had the same problem and created a Django app that is designed to be used for exactly such a case. It allows you to define default values for certain settings. It then first checks whether the setting is set in the global settings file. If not, it will return the default value.
I've extended it to also allow for some type checking or pre handling of the default value (e.g. a dotted class path can be converted to the class itself on load)
The app can be found at: https://pypi.python.org/pypi?name=django-pluggableappsettings&version=0.2.0&:action=display
In my apps, I have a seperate settings.py file. In that file I have a get() function that does a look up in the projects settings.py file and if not found returns the default value.
Then where I need to access APPLES I have:
This allows an override in the projects settings.py, getattr will check there first and return the value if the attribute is found or use the default defined in your apps settings file.
Here are two solutions. For both you can set
settings.py
files in your applications and fill them with default values.Configure default value for a single application
Use
from MYAPP import settings
instead offrom django.conf import settings
in your code.Edit
YOURAPP/__init__.py
:Configure default values for a whole project
Use
from MYPROJECT import settings
instead offrom django.conf import settings
in your code.Edit
MYPROJECT/MYPROJECT/__init__.py
This solution may seem more easier to install, but it does not guarantee that the good default value will be returned. If several applications declare the same variable in their settings.py, you can not be sure which one will return the default value you asked.
Starting from Mike's answer, I now wrapped the default setting handling into a class with easy to use interface.
Helper module:
Usage:
This prints the value from
django.conf.settings
, or the default if it isn't set there. Thissettings
object can also be used to access all the standard setting values.How about just: