Full reference for initial setup, environment config, and ongoing project maintenance.
- Prerequisites
- Virtual Environment
- Install Django
- Create Project & App
- Project Structure
- Settings Configuration
- Database Setup
- Environment Variables
- Static & Media Files
- Run Development Server
- User & Auth Setup
- Git & Version Control
- Requirements Management
- Update Workflow
- Production Checklist
- Common Commands Reference
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 -yInstall Python (Windows): Download from https://python.org — check "Add to PATH" during install.
Always isolate project dependencies. Never install Django globally.
Create:
python -m venv venvActivate:
# Linux / macOS
source venv/bin/activate
# Windows CMD
venv\Scripts\activate.bat
# Windows PowerShell
venv\Scripts\Activate.ps1Deactivate when done:
deactivateConfirm venv is active — prompt shows
(venv)prefix.
pip install --upgrade pip
pip install djangoInstall specific version:
pip install django==5.0.6Verify:
python -m django --versionCreate 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 myappRegister app in settings:
# myproject/settings.py
INSTALLED_APPS = [
...
'myapp',
]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
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')Install driver:
pip install psycopg2-binarySettings:
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'),
}
}Install driver:
pip install mssql-djangoSettings:
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',
},
}
}python manage.py makemigrations
python manage.py migrateInstall:
pip install python-dotenvCreate .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=5432Load in settings:
from dotenv import load_dotenv
load_dotenv()Never commit
.envto git. Add to.gitignore.
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 --noinputpython manage.py runserverCustom port:
python manage.py runserver 0.0.0.0:8080Access at: http://127.0.0.1:8000
Create superuser:
python manage.py createsuperuserCustom 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_MODELbefore running first migration. Changing later is painful.
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
Save dependencies:
pip freeze > requirements.txtInstall from requirements:
pip install -r requirements.txtRecommended — 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
Follow this order when updating the project:
git pull origin mainsource venv/bin/activatepip install -r requirements.txtpython manage.py migratepython manage.py collectstatic --noinput# Development
python manage.py runserver
# Production (systemd)
sudo systemctl restart gunicorn
sudo systemctl restart nginxpython manage.py shell -c "from django.core.cache import cache; cache.clear()"- Check logs for errors
- Test critical pages
- Confirm admin panel loads
Run this before going live:
python manage.py check --deploySettings:
# 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 whitenoiseGunicorn start command:
gunicorn myproject.wsgi:application --bind 0.0.0.0:8000 --workers 3WhiteNoise for static files (add to middleware):
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware', # right after SecurityMiddleware
...
]
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'| 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.