Search code examples
pythondjangowsgi

Can I (safely) override Django settings in a server side wsgi.py?


I want to deploy two Django web-apps (individual domains) that share the same source code/repository and, hence, the same settings file. (Hosted on pythonanywhere by the way). The only difference between the two is that they should access different data bases (which I would usually define in settings.py or .env).

As I see it, the only file that is unique to each web-app is their individual ...wsgi.py file (the one on the server not the one in the Django project folder). Thus, my idea is to use that file to specify each app's data base settings.

Is it possible to (safely) override settings in a wsgi file? How would I do it?

The current wsgi.py file looks like this:

# +++++++++++ DJANGO +++++++++++
# To use your own django app use code like this:
import os
import sys
#
## assuming your django settings file is at '/home/.../mysite/mysite/settings.py'
## and your manage.py is is at '/home/.../mysite/manage.py'
path = '/home/.../...'
if path not in sys.path:
    sys.path.append(path)
#
os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings'
#
## then:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Many thanks for your help!


Solution

  • I went for the following solution, based on Abdul Aziz Barkat comment. This requires only one shared settings file, however, allows to override default settings therein.

    In settings.py

    'SOME_VAR': os.getenv('WSGI_SOME_VAR') or config('SOME_VAR')
    

    In ...wsgi.py:

    os.environ['DJANGO_SETTINGS_MODULE'] = 'core.settings'
    os.environ['WSGI_SOME_VAR'] = 'SOME_VALUE'