Manage Django Development and Production Settings
While django makes it easy to get an application up and running locally, the default setting is unsuitible for production use. It is a good practice to break down the default settings.py
module into multiple files to seperate development settings and production settings.
Basic structure
An empty new django site looks like this:
|
|
We want to group different setting files together. So create a folder named settings
, rename the settings.py
file to base.py
and move it into the newly created settings
folder. Then we can create dev.py
and production.py
for development and production settings resepctively. Now the file structure would look like this:
|
|
Config setting files
The settings/base.py
file has all common settings in it. Other settings just extend base.py
module like this:
|
|
And production.py
module usually read senstive infomation like SECRET_KEY
from environment variable or local .env
file.
|
|
Use setting file on demand
Use it through command line
We can pass which settings.py
module to use in the coomand line when we start manage.py
:
|
|
Change manage.py
By default we start django site with manage.py
and it uses development as default setting:
|
|
We can change the line os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
to os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.dev")
for dev settings or os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.production")
for production settings.
Set environment variabel
From above we can see that django manage.py
actually use environment variable DJANGO_SETTINGS_MODULE
for specific setting module. We can set this variable before running django:
Unix bash shell:
|
|
or windows shell:
|
|