I am starting with Django development as a hobby project. So far I have happily worked with SQLite, both in development (i.e. with py manage.py runserver) and in deployment (on Nginx + uWSGI). Now I would also like to learn to use a more robust PostgreSQL database. However, if possible, I would like to skip installing it locally, to avoid installing Postgres on Windows.
I was wondering if it was possible, by means of Django, to use SQLite whenever I use the built-in server and Postgres in deployment, without changing the project code. Couldn't find how to do it.
I can use a workaround and make my deployment procedure change the settings on server each time I deploy. But that's kind of a hack.
You could split your settings.py in multiple settings file e.g.
[projectname]/
├── [projectname]/
│ ├── __init__.py
│ ├── settings/
│ │ │── base.py
│ │ │── development.py
│ │ │── production.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
your base.py includes all code from your current settings.py. specify the different databases in your development.py(sqlite3) and in your production.py (postgresql) and import the base.py in each
from .base import *
Last but not least you'll have to tell django which file it should use. Add
export DJANGO_SETTINGS_MODULE="projectname.settings.development"
to your postactivate of your virtualenv on your development server and
export DJANGO_SETTINGS_MODULE="projectname.settings.production"
on your production server. Don't forget to
unset DJANGO_SETTINGS_MODULE
in your predeactivate.
More infos are here: http://www.marinamele.com/taskbuster-django-tutorial/settings-different-environments-version-control btw. a great tutorial with a lot of best practices
replace settings.py with
settings/
│── __init__.py
│── base.py
│── development.py
│── production.py
in __init__.py
import os
app_stage = os.environ.get('DJANGO_APP_STAGE', 'dev')
if app_stage == 'prod':
from .production import *
else:
from .development import *
And finally when you launch app for production, make sure you set env DJANGO_APP_STAGE='prod'
Create your database settings in respective files and you are good to go.
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