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.
The default is False . blank: If True , the field is allowed to be blank in your forms. The default is False , which means that Django's form validation will force you to enter a value.
Default settings These defaults live in the module django/conf/global_settings.py . Here's the algorithm Django uses in compiling settings: Load settings from global_settings.py . Load settings from the specified settings file, overriding the global settings as necessary.
It is used if you run your Django app as standalone. It will load your settings and populate Django's application registry. You can read the detail on the Django documentation.
import settings will import the first python module named settings.py found in sys. path . Usually (in default django setups) it allows access only to your site defined settings file, which overwrites django default settings ( django. conf.
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.
from django.conf import settings def get(key, default): return getattr(settings, key, default) APPLES = get('APPLES', 1)
Then where I need to access APPLES I have:
from myapp import settings as myapp_settings myapp_settings.APPLES
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.
How about just:
getattr(app_settings, 'SOME_SETTING', 'default value')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With