Randy Tang
Randy Tang

Reputation: 4353

Same Django projects running on different databases

I am trying to run two identical Django projects on different databases, one for production using a certain port number (say, 80) and the other for testing using another port number (say, 8000). I also used Nginx and Gunicorn as the reverse proxy server and the application server, with Nginx listening to ports 80 and 8000 and forwarding to gunicorn of ports 8001 and 8002, respectively.

The problem is: how do I know the port number of the request in Django's settings.py so that the project can choose different databases?

Upvotes: 0

Views: 41

Answers (1)

Aayush Agrawal
Aayush Agrawal

Reputation: 1394

The standard practice for doing this in django is to create a local_settings.py file

Put this at the top of the local_settings.py file:

try:
    from settings import *
except ImportError:
    pass

Now in local_settings.py you must override the following variable:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'dbuser',
        'PASSWORD': 'dbpassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
    }
}

With different values for both projects

Then when running Django you need to set the following environment variable:

export DJANGO_SETTINGS_MODULE="appname.local_settings"

One way to bunch this all together is to create a run.sh file that first sets this variable, then runs gunicorn

To sum it up, settings.py is common between both projects, local_settings.py overrides those variables that are different between different projects

Upvotes: 1

Related Questions