Kimkorng

Deploying Django on Render

22 JUN, 2023

I. Django Configuration with Environment Variables

Install python-dotenv

First, install the python-dotenv package:

shell
pip install python-dotenv

Configure settings.py

Add the following to your settings.py file:

python
from pathlib import Path import os from dotenv import load_dotenv # Define the base directory BASE_DIR = Path(__file__).resolve().parent.parent # Load environment variables from .env file load_dotenv(BASE_DIR / '.env') # Retrieve the secret key from the environment variables SECRET_KEY = os.getenv('SECRET_KEY') # Set the debug mode based on environment variable DEBUG = os.getenv('DEBUG') == 'True' # Configure allowed hosts ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(' ')

Create an .env file

In the root directory of your project, create a file named .env with the following content:

env
SECRET_KEY=your_secret_key DEBUG=True ALLOWED_HOSTS=localhost 127.0.0.1 DATABASE_URL=your_database_url

II. Handling Static Files

Install whitenoise

Install whitenoise to serve static files efficiently:

shell
pip install whitenoise

Update settings.py

Modify your settings.py to include whitenoise:

python
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # ... ] if not DEBUG: STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

III. Database Configuration

Set Up PostgreSQL on Render

  1. In the Render dashboard, click "New" at the top right and select "PostgreSQL".

  2. Configure the PostgreSQL instance with:

    • Name: Your custom name
    • Database: Leave empty
    • User: Leave empty
    • Region: Choose the closest region
    • PostgreSQL Version: 15
    • Datadog API Key: Leave empty
    • Plan Type: Choose according to your needs
  3. In the "Connections" section, note the "Internal Database URL".

Image description

Install Required Packages

Install the necessary packages for PostgreSQL integration:

shell
pip install psycopg2-binary pip install dj-database-url pip install gunicorn

Configure settings.py

Update your settings.py for database configuration:

python
import dj_database_url if not DEBUG: DATABASES = { "default": dj_database_url.parse(os.getenv("DATABASE_URL")) } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }

IV. Setting Up the Web Service

Configure Render Web Service

  1. Name: Your custom name
  2. Region: The same as your database
  3. Branch: Your main branch (e.g., main)
  4. Root Directory: Leave empty
  5. Environment: Python 3
  6. Build Command: sh build.sh
  7. Start Command: gunicorn core.wsgi:application
  8. Plan Type: Choose according to your needs

Add Environment Variables

Under the "Advanced" dropdown, add the following environment variables:

  1. PYTHON_VERSION: 3.9.9
  2. SECRET_KEY: Click "Generate" to create a new key
  3. DEBUG: False
  4. ALLOWED_HOSTS: *
  5. DATABASE_URL: Your internal database URL from Render

V. Build Script

Create build.sh

In the root directory, create a file named build.sh with the following content:

shell
#!/usr/bin/env bash set -o errexit # exit on error pip install -r requirements.txt python manage.py collectstatic --no-input python manage.py migrate

This script installs the required packages, collects static files, and applies database migrations.

SHARE