Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use SQLite for Django locally and Postgres on server

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.

like image 678
texnic Avatar asked Mar 10 '23 15:03

texnic


2 Answers

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

like image 142
Kroenig Avatar answered Mar 13 '23 03:03

Kroenig


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.

like image 35
Justin M. Ucar Avatar answered Mar 13 '23 03:03

Justin M. Ucar