Django

⌘K
  1. Home
  2. Django
  3. Hosting
  4. configure

configure

Got it! I’ll now provide a complete Django project setup named config, including:

Database Setup (SQLite for development, MySQL/PostgreSQL for production)
Environment Variables (.env using python-decouple)
Static Files & Media Configuration (whitenoise for production)
Gunicorn for Production Server
Procfile for Deployment (for platforms like Heroku, cPanel)
Best Practices for Development & Production


🚀 Complete Django Project Setup (Production & Development Ready)

Step 1: Install Django and Required Packages

Open a terminal and run:

pip install django python-decouple gunicorn whitenoise mysqlclient psycopg2-binary

📌 Packages Explanation:

  • python-decouple → Manage .env file for environment variables.
  • gunicorn → WSGI server for production deployment.
  • whitenoise → Serve static files in production without needing Nginx.
  • mysqlclient → Connect Django with MySQL.
  • psycopg2-binary → Connect Django with PostgreSQL.

Step 2: Create a Django Project

Run the following command to create a Django project named config:

django-admin startproject config .

Step 3: Create & Configure .env File

Create a folder envs inside your project directory and add a .env file:

mkdir envs
touch envs/.env

Now open envs/.env and add the following:

📌 For Local Development (SQLite)

DEBUG=True
SECRET_KEY=my-secret-key
DATABASE_ENGINE=sqlite
ALLOWED_HOSTS=127.0.0.1,localhost

📌 For Production (MySQL / PostgreSQL)

DEBUG=False
SECRET_KEY=my-secret-key
DATABASE_ENGINE=postgresql
ALLOWED_HOSTS=yourdomain.com

# Database Credentials (For MySQL or PostgreSQL)
DB_NAME=mydatabase
DB_USER=mydbuser
DB_PASSWORD=mypassword
DB_HOST=localhost
DB_PORT=5432   # Change to 3306 for MySQL

Step 4: Configure settings.py

Open config/settings.py and update the following:

import os
from decouple import config, Csv

# SECURITY CONFIG
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', default="127.0.0.1,localhost", cast=Csv())

# DATABASE CONFIGURATION
DATABASE_ENGINE = config('DATABASE_ENGINE', default='sqlite')

if DATABASE_ENGINE == 'sqlite':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
elif DATABASE_ENGINE == 'mysql':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            'NAME': config('DB_NAME'),
            'USER': config('DB_USER'),
            'PASSWORD': config('DB_PASSWORD'),
            'HOST': config('DB_HOST', default='localhost'),
            'PORT': config('DB_PORT', default='3306'),
        }
    }
elif DATABASE_ENGINE == 'postgresql':
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql',
            'NAME': config('DB_NAME'),
            'USER': config('DB_USER'),
            'PASSWORD': config('DB_PASSWORD'),
            'HOST': config('DB_HOST', default='localhost'),
            'PORT': config('DB_PORT', default='5432'),
        }
    }
else:
    raise ValueError("Invalid DATABASE_ENGINE in .env file!")

# STATIC & MEDIA FILES CONFIGURATION
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

# Production Static Configuration
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

# Middleware (Add Whitenoise)
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # Add Whitenoise Middleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

# TEMPLATES
TEMPLATES_DIR = os.path.join(BASE_DIR, 'templates')
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATES_DIR],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

Update urls.py

Open config/urls.py and modify it:

from django.conf.urls.static import static
from django.conf import settings
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
]

# Serve static files in development
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Step 2: Explanation

  1. static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
    • Serves static files (CSS, JS, images) in development mode.
    • In production, whitenoise will handle this automatically.
  2. static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    • Serves uploaded media files (user uploads like profile pictures) in development mode.
    • In production, a web server like Nginx or cPanel’s file handler should serve media files.

Step 5: Create Static, Media, and Template Folders

Run the following:

mkdir static media templates
touch static/.gitkeep media/.gitkeep templates/.gitkeep

Now, Django will automatically store static files in static/ and uploaded media files in media/.


Step 6: Apply Migrations & Create Superuser

Run:

python manage.py migrate
python manage.py createsuperuser

Follow the prompts to create an admin account.


Step 7: Configure Procfile for Gunicorn

Create a Procfile in the root project directory:

touch Procfile

Now, add this inside Procfile:

web: gunicorn config.wsgi --log-file -

Step 8: Test Gunicorn Locally

Run Gunicorn to check if it works:

gunicorn config.wsgi

To bind to all interfaces (useful for cloud platforms like AWS):

gunicorn --bind 0.0.0.0:8000 config.wsgi

Stop the server with CTRL + C.


Step 9: Set Up Static Files for Production

Run:

python manage.py collectstatic

This command will move all static files to staticfiles/ so whitenoise can serve them efficiently.


Step 10: Deploy on cPanel

  1. Upload your Django project to cPanel.
  2. Set up Python Environment (Python 3.9+).
  3. Install Dependencies inside cPanel Terminal: pip install -r requirements.txt
  4. Set up Procfile and run Gunicorn.
  5. Set up MySQL/PostgreSQL Database in cPanel.

🎯 Final Summary

✅ Installed Django, python-decouple, gunicorn, whitenoise, mysqlclient, psycopg2-binary.
✅ Set up SQLite (Development), MySQL/PostgreSQL (Production).
✅ Configured Static, Media, Templates directories.
✅ Added Whitenoise for better static file handling.
✅ Set up Gunicorn for production.
✅ Created a Procfile for easy deployment.
cPanel Deployment Steps included.

Now, your Django project is fully production-ready! 🚀🔥 Let me know if you need any extra details. 😊

How can we help?