Skip to content

Instantly share code, notes, and snippets.

@imrankabir02
Created May 18, 2026 11:28
Show Gist options
  • Select an option

  • Save imrankabir02/58fa754f63fa98be0076f22e6261e1a5 to your computer and use it in GitHub Desktop.

Select an option

Save imrankabir02/58fa754f63fa98be0076f22e6261e1a5 to your computer and use it in GitHub Desktop.

Django Project Setup & Update Guide

Full reference for initial setup, environment config, and ongoing project maintenance.


Table of Contents

  1. Prerequisites
  2. Virtual Environment
  3. Install Django
  4. Create Project & App
  5. Project Structure
  6. Settings Configuration
  7. Database Setup
  8. Environment Variables
  9. Static & Media Files
  10. Run Development Server
  11. User & Auth Setup
  12. Git & Version Control
  13. Requirements Management
  14. Update Workflow
  15. Production Checklist
  16. Common Commands Reference

1. Prerequisites

Install these before starting:

Tool Minimum Version Check Command
Python 3.10+ python --version
pip latest pip --version
git 2.x git --version
PostgreSQL / MSSQL depends on DB choice

Install Python (Ubuntu/Debian):

sudo apt update
sudo apt install python3 python3-pip python3-venv -y

Install Python (Windows): Download from https://python.org — check "Add to PATH" during install.


2. Virtual Environment

Always isolate project dependencies. Never install Django globally.

Create:

python -m venv venv

Activate:

# Linux / macOS
source venv/bin/activate

# Windows CMD
venv\Scripts\activate.bat

# Windows PowerShell
venv\Scripts\Activate.ps1

Deactivate when done:

deactivate

Confirm venv is active — prompt shows (venv) prefix.


3. Install Django

pip install --upgrade pip
pip install django

Install specific version:

pip install django==5.0.6

Verify:

python -m django --version

4. Create Project & App

Create project:

django-admin startproject myproject .

The trailing . places files in current directory. Omit it to nest inside a subdirectory.

Create app:

python manage.py startapp myapp

Register app in settings:

# myproject/settings.py
INSTALLED_APPS = [
    ...
    'myapp',
]

5. Project Structure

myproject/
├── manage.py
├── myproject/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── asgi.py
│   └── wsgi.py
├── myapp/
│   ├── migrations/
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py          ← create this manually
│   └── views.py
├── templates/           ← create this manually
├── static/              ← create this manually
├── media/               ← create this manually
├── .env
├── .gitignore
└── requirements.txt

6. Settings Configuration

Split settings for maintainability:

myproject/
├── settings/
│   ├── __init__.py
│   ├── base.py       ← shared settings
│   ├── dev.py        ← development overrides
│   └── prod.py       ← production overrides

base.py essentials:

from pathlib import Path
import os
from dotenv import load_dotenv

load_dotenv()

BASE_DIR = Path(__file__).resolve().parent.parent.parent

SECRET_KEY = os.environ.get('SECRET_KEY')

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', '').split(',')

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # third-party
    # local apps
    'myapp',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates'],
        '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',
            ],
        },
    },
]

LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_TZ = True

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

dev.py:

from .base import *

DEBUG = True

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

Update manage.py to use split settings:

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings.dev')

7. Database Setup

PostgreSQL

Install driver:

pip install psycopg2-binary

Settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': os.environ.get('DB_HOST', 'localhost'),
        'PORT': os.environ.get('DB_PORT', '5432'),
    }
}

MSSQL (SQL Server)

Install driver:

pip install mssql-django

Settings:

DATABASES = {
    'default': {
        'ENGINE': 'mssql',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': os.environ.get('DB_HOST'),
        'PORT': os.environ.get('DB_PORT', '1433'),
        'OPTIONS': {
            'driver': 'ODBC Driver 17 for SQL Server',
        },
    }
}

Run Migrations

python manage.py makemigrations
python manage.py migrate

8. Environment Variables

Install:

pip install python-dotenv

Create .env file:

SECRET_KEY=your-very-secret-key-here
DEBUG=True
ALLOWED_HOSTS=localhost,127.0.0.1

DB_NAME=mydb
DB_USER=myuser
DB_PASSWORD=mypassword
DB_HOST=localhost
DB_PORT=5432

Load in settings:

from dotenv import load_dotenv
load_dotenv()

Never commit .env to git. Add to .gitignore.


9. Static & Media Files

Settings:

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'   # for collectstatic

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

Serve media in dev (urls.py):

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

Collect static for production:

python manage.py collectstatic --noinput

10. Run Development Server

python manage.py runserver

Custom port:

python manage.py runserver 0.0.0.0:8080

Access at: http://127.0.0.1:8000


11. User & Auth Setup

Create superuser:

python manage.py createsuperuser

Custom user model (recommended — do this before first migration):

# myapp/models.py
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    pass  # extend fields here
# settings/base.py
AUTH_USER_MODEL = 'myapp.CustomUser'

Set AUTH_USER_MODEL before running first migration. Changing later is painful.


12. Git & Version Control

Initialize:

git init
git add .
git commit -m "Initial Django project setup"

.gitignore for Django:

# Python
__pycache__/
*.py[cod]
*.pyo
*.pyd

# Virtual environment
venv/
env/
.venv/

# Django
*.log
db.sqlite3
/staticfiles/
/media/

# Environment
.env
*.env

# IDE
.vscode/
.idea/
*.swp

13. Requirements Management

Save dependencies:

pip freeze > requirements.txt

Install from requirements:

pip install -r requirements.txt

Recommended — split by environment:

requirements/
├── base.txt        ← shared packages
├── dev.txt         ← dev-only (debug toolbar, faker, etc.)
└── prod.txt        ← prod-only (gunicorn, whitenoise, etc.)

dev.txt:

-r base.txt
django-debug-toolbar
faker

prod.txt:

-r base.txt
gunicorn
whitenoise

14. Update Workflow

Follow this order when updating the project:

Step 1 — Pull latest code

git pull origin main

Step 2 — Activate venv

source venv/bin/activate

Step 3 — Install new/updated packages

pip install -r requirements.txt

Step 4 — Apply migrations

python manage.py migrate

Step 5 — Collect static (production only)

python manage.py collectstatic --noinput

Step 6 — Restart server

# Development
python manage.py runserver

# Production (systemd)
sudo systemctl restart gunicorn
sudo systemctl restart nginx

Step 7 — Clear cache (if using Redis/Memcached)

python manage.py shell -c "from django.core.cache import cache; cache.clear()"

Step 8 — Verify

  • Check logs for errors
  • Test critical pages
  • Confirm admin panel loads

15. Production Checklist

Run this before going live:

python manage.py check --deploy

Settings:

# prod.py
DEBUG = False
ALLOWED_HOSTS = ['yourdomain.com', 'www.yourdomain.com']

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
X_FRAME_OPTIONS = 'DENY'

Install production packages:

pip install gunicorn whitenoise

Gunicorn start command:

gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3

WhiteNoise for static files (add to middleware):

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # right after SecurityMiddleware
    ...
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

16. Common Commands Reference

Task Command
Start project django-admin startproject myproject .
Create app python manage.py startapp myapp
Run server python manage.py runserver
Make migrations python manage.py makemigrations
Apply migrations python manage.py migrate
Show migrations python manage.py showmigrations
Rollback migration python manage.py migrate myapp 0003
Create superuser python manage.py createsuperuser
Open shell python manage.py shell
Open DB shell python manage.py dbshell
Collect static python manage.py collectstatic
Run tests python manage.py test
Check deployment python manage.py check --deploy
Flush database python manage.py flush
Load fixtures python manage.py loaddata fixture.json
Dump data python manage.py dumpdata myapp > data.json
Clear sessions python manage.py clearsessions

Generated for Django 4.x / 5.x projects. Tested on Ubuntu 22.04 and Windows 11.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment