1

Environment Variables

pip install python-dotenv

settings.py:

import os
from dotenv import load_dotenv

load_dotenv()

This is for Django to recognize and read our environment variables.

Secret Key:

Save your SECRET_KEY somewhere, and replace it with this.

SECRET_KEY = os.getenv('SECRET_KEY')

Debug:

DEBUG = os.getenv('DEBUG') == '1'

Note: This means that if the DEBUG(environment variable) is equal to '1', then DEBUG is True.

Allowed Hosts:

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "127.0.0.1").split(",")

The split() method splits the DJANGO_ALLOED_HOSTS environment variables where the "," exist, and turns the string variable into a list.

Database:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}

DB_NAME = os.getenv("DB_NAME")  # database name
DB_PASSWORD = os.getenv("DB_PASSWORD")  # database user password
DB_USER = os.getenv("DB_USER")  # database username
DB_HOST = os.getenv("DB_HOST")  # database host

MYSQL_READY = (
    DB_NAME is not None
    and DB_PASSWORD is not None
    and DB_USER is not None
    and DB_HOST is not None
)

if MYSQL_READY:
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.mysql",
            "NAME": DB_NAME,
            "USER": DB_USER,
            "PASSWORD": DB_PASSWORD,
            "HOST": DB_HOST,
            "OPTIONS": {
                "init_command": "SET sql_mode='STRICT_TRANS_TABLES'",
            },
        }
    }

This code means that if the DB_NAME, DB_PASSWORD, DB_USER, and DB_HOST are set in the .env file, django will use the MySQL database with the given configuration.

Create a .env file:

Create a file and call it .env, then:

SECRET_KEY=<your_secret_key>
DEBUG=1
DB_NAME=<db_name>
DB_PASSWORD=<db_password>
DB_USER=<db_user>
DB_HOST=<db_host>

Note: This file should not be staged to version control.

Push your code:

Push your code to GitHub(or any remote repository) to be able to clone it in PythonAnywhere.

Important Note: You have to make sure not to stage your .env file to the version control (git), because the purpose of the .env file and environment variables is to keep the Development environment and the Production separated.

For that, you'll need to add your .env file to .gitignore.

1012
Mohamed
El Firdoussi