Y.N
Y.N

Reputation: 5257

django settings.py for pythonanywhere

I have the django application, which I developing locally and deploying to pythonanywhere.

Local Setting.py contain the sqlite-db, local static paths etc. Setting.py on pythonanywhere contain mysql-db, cdn links for static etc.

I want to have one settings file in my git, with some checks like this

if host_type=='pythonanywhere':
    DATABASES = { "default": { "ENGINE": "django.db.backends.mysql",

Where is a best practice for settings.py for this?

And which os.environ's are provided by pythonanywhere?

Upvotes: 3

Views: 1210

Answers (2)

Joe P
Joe P

Reputation: 485

I have been using python-dotenv (from pip) and a ~/.env file (which is excluded from git) on my pythonanywhere account.

Then in my settings.py:

from dotenv import load_dotenv
load_dotenv()
SECRET_KEY = os.getenv('DJANGO_SECRET_KEY')

This means the only file unique to pythonanywhere is the .env file, and the same approach works locally, and (reading env vars directly not with dotenv) on Heroku where a settings.py file excluded from git isn't possible.

Upvotes: 2

hwjp
hwjp

Reputation: 16071

PythonAnywhere doesn't give you a UI for setting environment variables, although you could edit your /home/yourusername/.bashrc file and set one in there using

export MY_ENV_VAR="something"

From your question, I'm guessing you want to avoid storing your database settings in version control. So, as an alternative to environment variables, one technique I've used is to have a file, outside of version control, which contains custom settings:

echo "production_settings.py" >> .gitignore

in settings.py:

#... default dev settings
DATABASES = { "default": {"ENGINE": "django.db.backends.sqlite3" 
#...
try:
    from production_settings import DATABASES
except ImportError:
    pass

So on PythonAnywhere, you can keep your production settings in a file called production_settings.py, and on your dev machine, you do nothing at all.

You could also use this method to set a custom SECRET_KEY on the server, which would be good security practice...

Upvotes: 5

Related Questions