AGENT SKILL

django-deployment

Deploy Django applications to Vercel with Supabase PostgreSQL backend. Covers project restructuring, Vercel config, WSGI serverless handler, Supabase database provisioning, and environment management.

License 许可
MIT
最近更新
2026-08-16
Stars
★ 0
Forks
0

01 前言 Front Matter

name
django-deployment
author
Hermes
license
MIT
version
1.0.0
metadata
{ "hermes": { "tags": [ "Django", "Vercel", "Supabase", "PostgreSQL", "Deployment", "Python", "DevOps" ] } }
platforms
[ "linux", "macos" ]
description
Deploy Django applications to Vercel with Supabase PostgreSQL backend. Covers project restructuring, Vercel config, WSGI serverless handler, Supabase database provisioning, and environment management.

02 资源文件 3

03 SKILL.md 正文

Django Deployment (Vercel + Supabase)

Deploy a Django application to Vercel's serverless platform with Supabase PostgreSQL as the database backend.

When to Use

  • Migrating a Django app off Render / Heroku / traditional VPS
  • Deploying a Django REST API that needs PostgreSQL
  • Replacing sqlite3 dev databases with production PostgreSQL
  • User's hosting subscription (e.g. Render) has expired and they need a free/cheap alternative

Prerequisites

  • Vercel CLI installed and authenticated (vercel login or VERCEL_TOKEN env)
  • Supabase account with an access token (from supabase.com/dashboard/account/tokens)
  • GitHub repo for the project (Vercel links to GitHub)
  • Python 3.11+ project with Django

Step-by-Step Workflow

Phase 1 — Prepare the Codebase

1a. Fix the api/ directory conflict

Vercel treats every .py file in an api/ directory as a serverless function endpoint. If your Django app has an api/ app, rename it to avoid conflict:

cd /path/to/project
mv api api_app
mkdir -p api
touch api/__init__.py

Then update all references:

File Change
backend/settings.py — INSTALLED_APPS "api" → "api_app"
backend/settings.py — LOGGING logger name "api" → "api_app"
backend/urls.py include('api.urls') → include('api_app.urls')
api_app/apps.py name = 'api' → name = 'api_app'
Any migration files referencing 'api' Update to 'api_app'

The remaining api/ directory now contains only the Vercel handler (below).

1b. Create api/index.py — Vercel WSGI handler

import os
import sys

# Add project root to path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)

# Set Django settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "backend.settings")

# Build-time SECRET_KEY fallback (Vercel replaces at runtime with real env var)
if not os.environ.get("DJANGO_SECRET_KEY"):
    os.environ["DJANGO_SECRET_KEY"] = "build-time-fallback-insecure-key"

# Bootstrap Django
import django
django.setup()

# WSGI application
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

# Vercel Python Runtime handler using serverless-wsgi
from serverless_wsgi import handle

def handler(request, context=None):
    return handle(application, request, context)

1c. Create vercel.json

{
  "buildCommand": "pip install -r requirements.txt && python manage.py collectstatic --noinput",
  "outputDirectory": "staticfiles",
  "framework": null,
  "functions": {
    "api/**/*.py": {
      "runtime": "python3.12",
      "maxDuration": 60
    }
  },
  "routes": [
    { "src": "/static/(.*)", "dest": "/static/$1" },
    { "src": "/media/(.*)", "dest": "/media/$1" },
    { "src": "/(.*)", "dest": "/api/index.py" }
  ]
}

1d. Add serverless-wsgi to requirements

serverless-wsgi==2.0.0

1e. Update .gitignore

Add Vercel artifacts:

.vercel
.vercelignore

Phase 2 — Set Up Supabase PostgreSQL

2a. Get Supabase access token

Direct user to: https://supabase.com/dashboard/account/tokens → Generate New Token (name it after the project, e.g. JENGA-CONNECT-Deploy) → Copy the sbp_... token

2b. Sign in with Supabase CLI (if available)

supabase login --token sbp_xxxxx

If Supabase CLI is not installed, have the user create a project manually at: https://supabase.com/dashboard/projects → New Project → pick region closest to users (e.g. South Africa for Tanzania) → note the database password

2c. Get the PostgreSQL connection string

supabase projects list
supabase projects create JENGA-CONNECT --org-id <org>

Or from the dashboard: Project Settings → Database → Connection string (URI)

Format:

postgresql://postgres:[PASSWORD]@db.[REF].supabase.co:5432/postgres

The connection string goes into Vercel env as DATABASE_URL.

Phase 3 — Deploy to Vercel

3a. Set Vercel environment variables

vercel env add DATABASE_URL
vercel env add DJANGO_SECRET_KEY  # generate: python -c 'import secrets; print(secrets.token_urlsafe(64))'
vercel env add DJANGO_DEBUG False
vercel env add DJANGO_ALLOWED_HOSTS ".vercel.app,jengaconnect.cc"
vercel env add DJANGO_SECURE_SSL_REDIRECT True

Mark production-only variables as "Production" scope.

3b. Deploy

vercel --prod

First deploy will likely fail on collectstatic if SECRET_KEY is missing — the build-time fallback in api/index.py handles this. After first deploy succeeds, verify:

  • Health check: curl https://project.vercel.app/
  • Django admin: https://project.vercel.app/admin/
  • API endpoints: https://project.vercel.app/api/

Phase 4 — Database Migrations

After deploy, run migrations:

vercel env pull .env.production  # pulls production env vars
python manage.py migrate --run-syncdb

Or use Vercel CLI's vc run for one-off commands (if supported):

vercel run python manage.py migrate

Phase 5 — Custom Domain (Optional)

vercel domains add jengaconnect.cc
# Add CNAME record at your DNS provider pointing to cname.vercel-dns.com

Environment Variables Reference

Variable Required Description Example
DATABASE_URL ✅ PostgreSQL connection string from Supabase postgresql://postgres:xxx@db.xxx.supabase.co:5432/postgres
DJANGO_SECRET_KEY ✅ Django secret (64+ chars, random) python -c 'import secrets; print(secrets.token_urlsafe(64))'
DJANGO_DEBUG ✅ Must be False for production False
DJANGO_ALLOWED_HOSTS ✅ Comma-separated allowed hosts .vercel.app,jengaconnect.cc
DJANGO_SECURE_SSL_REDIRECT ✅ Enforce HTTPS True
CLOUDINARY_CLOUD_NAME ⬜ If using Cloudinary media storage —
CLOUDINARY_API_KEY ⬜ Cloudinary API key —
CLOUDINARY_API_SECRET ⬜ Cloudinary API secret —

Common Pitfalls

  1. api/ app conflict: Vercel treats every .py in api/ as a serverless function. If Django has an api app, rename it to api_app before deploying. Undetected until deploy time when import errors appear.

  2. Build-time SECRET_KEY not set: Django's collectstatic runs during build and needs DJANGO_SECRET_KEY. The handler must set a build-time fallback before django.setup().

  3. Static files 404: Ensure whitenoise is in middleware (SecurityMiddleware first, then WhiteNoiseMiddleware) and STATIC_ROOT / STATICFILES_STORAGE are configured.

  4. SQLite vs PostgreSQL: The production DATABASE_URL points to Supabase PostgreSQL. Local .env may use sqlite3 — the dj-database-url config picks whichever DATABASE_URL is set.

  5. Database not migrated: Vercel deploys the app but doesn't run migrate. Must be done manually or via a post-deploy hook.

  6. Vercel CLI not authenticated: If vercel projects ls fails with "token not valid", the user needs to run vercel login or provide a token from vercel.com/account/tokens.

  7. Python runtime version: Vercel supports Python 3.12. Pin it in vercel.json functions config. Check with python3 --version.

Verification Checklist

  • [ ] Django admin loads at /admin/
  • [ ] API endpoints return JSON (not 500)
  • [ ] Static files load (CSS, JS, images)
  • [ ] Database connection works (check admin data)
  • [ ] Media uploads work (if using Cloudinary/local)
  • [ ] HTTPS enforced (redirects HTTP → HTTPS)
  • [ ] DJANGO_DEBUG=False in production

04 同仓库更多 Skills