I was wondering about whether it is better to import variables into your view from the settings.py file? or better to create a configuration file with the variables that are needed?
I tend to like to write configuration files for my Django applications, read, and import the variables from there when necessary. For example:
.configrc
[awesomeVariables]
someMagicNumber = 7
views.py
from ConfigParser import SafeConfigParser
#Open and parse the file
config = SafeConfigParser()
config.read(pathToConfig)
#Get variable
magicNumber = config.get('awesomeVariables', 'someMagicNumber'))
However, I've noticed some programmers prefer the following :
settings.py
SOME_MAGIC_NUMBER=7
views.py
import settings
magicNumber = settings.SOME_MAGIC_NUMBER
I was curious as to the pros and cons of the different methods? Can importing variables directly from your settings compromise the integrity of the architecture?
settings.py is a core file in Django projects. It holds all the configuration values that your web app needs to work; database settings, logging configuration, where to find static files, API keys if you work with external APIs, and a bunch of other stuff.
Create a settings.py file in your application's package (for example, if your application is named "myapp", put it in the filesystem directory named myapp ; the one with an __init__.py in it.
settings.py contains all the website settings, including registering any applications we create, the location of our static files, database configuration details, etc.
It's a judgement call. Using the settings module is the "Django way", although you should do from django.conf import settings; settings.MY_SETTING
, which will respect DJANGO_SETTINGS_MODULE
. But Django is just Python; there's nothing that will stop you from using ConfigParser
. In the interest of having only one place where such things are defined, I'd recommend putting it in the Django settings file - but if you have a reason not to, don't.
Using a config file is completely un-Django. Settings go in settings.py. Period. For app-specific settings, you simply set a default in your app and allow the user to override in their project's settings.py:
from django.conf import settings
SOME_MAGIC_NUMBER = settings.SOME_MAGIC_NUMBER if hasattr(settings, 'SOME_MAGIC_NUMBER') else 0
# Where `0` is the default value
There also an app for storing settings dynamically in db. Maybe you find it usefull . django-constance
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