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 资源文件 5
- 参考文档references/api-directory-conflict.md2.2 KB
- 参考文档references/supabase-connection-troubleshooting.md5.9 KB
- 参考文档references/vercel-services-migration.md3.5 KB
- 参考文档templates/api-index-py.txt827 B
- 参考文档templates/vercel.json706 B
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 loginor 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
⚠️ Vercel CLI v54+ uses a new "services" architecture that auto-detects Django and rejects the old top-level
buildCommand/functions/outputDirectoryformat. The template below works on both old and new CLI versions. Seereferences/vercel-services-migration.mdfor the full migration story.
Recommended — use the services format and skip collectstatic (whitenoise serves static files at runtime):
{
"version": 2,
"services": {
"jengaconnect": {
"root": ".",
"entrypoint": "api/index.py",
"runtime": "python",
"buildCommand": "echo 'Static files served by whitenoise at runtime'"
}
},
"rewrites": [
{
"source": "/(.*)",
"destination": {
"type": "service",
"service": "jengaconnect"
}
}
],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "DENY" },
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" }
]
}
]
}
Critical differences from old format:
"runtime": "python"(NOT"python3.12"— v54 rejects version suffixes)- No
maxDuration,config, oroutputDirectoryinsideservicesblock installCommandinside the services block IS valid (contrary to some docs)routes→rewriteswith{"type": "service", "service": "<name>"}destinations- The service name (here
jengaconnect) must match when referenced in rewrites
Alternative — old format (still works on Vercel CLI < v54):
{
"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 → Transaction mode tab
⚠️ Copy the exact URI from the dashboard — don't construct it manually. The format varies:
- Some projects:
postgresql://postgres.[REF]:[PASSWORD]@aws-0-[region].pooler.supabase.com:6543/postgres- Others:
postgresql://postgres:[PASSWORD]@aws-0-[region].pooler.supabase.com:6543/postgresURL-encode special characters in the password (
//→%2F%2F,@→%40, etc.).
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,yourdomain.cc |
DJANGO_SECURE_SSL_REDIRECT |
✅ | Enforce HTTPS | True |
DJANGO_CSRF_TRUSTED_ORIGINS |
⬜ | Comma-separated HTTPS origins for CSRF | https://yourdomain.cc,https://project.vercel.app |
DJANGO_CORS_ALLOWED_ORIGINS |
⬜ | Comma-separated HTTPS origins for CORS | https://yourdomain.cc,https://project.vercel.app |
USE_LOCAL_CACHE |
⬜ | true to use LocMemCache instead of Redis |
true |
FRONTEND_URL |
⬜ | Canonical domain for payment callbacks | https://yourdomain.cc |
CLOUDINARY_CLOUD_NAME |
⬜ | If using Cloudinary media storage | — |
CLOUDINARY_API_KEY |
⬜ | Cloudinary API key | — |
CLOUDINARY_API_SECRET |
⬜ | Cloudinary API secret | — |
STRIPE_PUBLIC_KEY |
⬜ | Stripe publishable key (if integrating) | pk_live_... |
STRIPE_SECRET_KEY |
⬜ | Stripe secret key | sk_live_... |
STRIPE_WEBHOOK_SECRET |
⬜ | Stripe webhook signing secret | whsec_... |
Set env vars with: vercel env add <VAR_NAME> production <<< "<value>"
Common Pitfalls
-
api/app conflict: Vercel treats every.pyinapi/as a serverless function. If Django has anapiapp, rename it toapi_appbefore deploying. Undetected until deploy time when import errors appear. -
Build-time SECRET_KEY not set: Django's
collectstaticruns during build and needsDJANGO_SECRET_KEY. The handler must set a build-time fallback beforedjango.setup(). Also add a fallback insettings.pyitself:SECRET_KEY = os.getenv("DJANGO_SECRET_KEY") or "build-time-fallback". -
Vercel CLI v54+ auto-detection rejects old vercel.json: The new CLI auto-detects Django and tries to create a
servicesconfig. Top-levelbuildCommand,functions,outputDirectory,installCommandconflict with this. Use the services format (see section 1c above) or create the project first withvercel project add <name>then link withvercel link --project <name>. -
Vercel project name too long: When auto-detection tries to create a project from the directory name, the generated name can exceed Vercel's 100-char limit. Fix: create the project explicitly first (
vercel project add shortname) then link it (vercel link --project shortname). -
collectstaticfails during build: TheDATABASE_URLenv var may have a placeholder password during build, causingdj_database_url.config()to crash at import time. Fix: guard the database config insettings.py:_db_url = os.getenv("DATABASE_URL", "") if _db_url and "placeholder" not in _db_url: DATABASES = {"default": dj_database_url.config(default=_db_url)} else: DATABASES = {"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3"}}Or skip
collectstaticentirely in the build command and let whitenoise serve static files at runtime. -
Static files 404: Ensure
whitenoiseis in middleware (SecurityMiddlewarefirst, thenWhiteNoiseMiddleware) andSTATIC_ROOT/STATICFILES_STORAGEare configured. -
SQLite vs PostgreSQL: The production
DATABASE_URLpoints to Supabase PostgreSQL. Local.envmay use sqlite3 — thedj-database-urlconfig picks whicheverDATABASE_URLis set. -
Database not migrated: Vercel deploys the app but doesn't run
migrate. Must be done manually or via a post-deploy hook. -
DisallowedHost error: After first deploy, Django returns 400 "DisallowedHost" if the Vercel staging URL isn't in
DJANGO_ALLOWED_HOSTS. Add.vercel.appplus your custom domain to the allowed hosts env var. -
Vercel CLI not authenticated: If
vercel projects lsfails with "token not valid", the user needs to runvercel loginor provide a token fromvercel.com/account/tokens. -
Supabase connection string format varies by project: Newer Supabase projects use
postgres.[project-ref]as the username in the pooler URI, but some projects reject this and expect justpostgres. The pooler hostname also varies by AWS region. Always get the exact connection string from Supabase Dashboard → Settings → Database → Connection string → Transaction mode. Three formats exist:- Pooler Transaction (recommended for serverless):
postgresql://postgres.[ref]:pw@aws-0-[region].pooler.supabase.com:6543/postgres - Pooler Session:
postgresql://postgres.[ref]:pw@aws-0-[region].pooler.supabase.com:5432/postgres - Direct:
postgresql://postgres.[ref]:pw@db.[ref].supabase.co:5432/postgres
See
references/supabase-connection-troubleshooting.mdfor full diagnostics and failure modes.Diagnostic command to verify connectivity:
timeout 5 nc -zv aws-0-us-east-2.pooler.supabase.com 6543 - Pooler Transaction (recommended for serverless):
-
Supabase free-tier database pauses after inactivity: If a page that queries the DB returns 500 or times out while static pages (login form, robots.txt) work fine, the database is likely paused. Fix: go to Supabase Dashboard → Database → click Restore/Resume. Free-tier projects pause after ~1 week of no requests. Symptom: homepage hangs for 50 seconds (Vercel timeout), but login/register pages (no DB on GET) return 200.
-
Special characters in DB password break connection strings: Characters like
//,@,#,%in the Supabase password must be URL-encoded in theDATABASE_URL. For example,Ma2//macpx20→Ma2%2F%2Fmacpx20. Thedj-database-urllibrary does NOT auto-encode — the env var must contain the encoded form. Test with:import urllib.parse print(urllib.parse.quote('Ma2//macpx20', safe='')) # Ma2%2F%2Fmacpx20⚠️ Users often typo passwords when sharing in chat. If the user shares credentials in a file attachment AND in chat, ALWAYS prefer the file — attachments are more reliable.
-
DB connection timeout causes Vercel 50s timeout: If the Supabase pooler is unreachable (wrong region, paused, DNS issue), the Django request hangs until Vercel's 50-second limit kills it. Always set connection timeouts in
settings.py:_db_config.setdefault("OPTIONS", {}) _db_config["OPTIONS"].setdefault("connect_timeout", 5) _db_config["OPTIONS"].setdefault("options", "-c statement_timeout=10000") -
Vercel Lambda CANNOT do IPv6. This is the #1 blocker for new Supabase projects. If
db.[REF].supabase.coonly has an AAAA record (IPv6), Vercel serverless functions will fail with "Cannot assign requested address". You MUST use the pooler connection, not direct. If the pooler also fails (see pitfall #16), the user must either: (a) enable the Supabase IPv4 add-on ($1/mo), or (b) wait for the pooler to be provisioned (can take hours for new projects). -
New Supabase projects may lack pooler provision. Symptom: every pooler region returns "tenant/user [REF] not found" (ENOTFOUND) and direct connection is IPv6-only. This means neither path works from Vercel. Diagnostic sequence:
# Check if pooler exists for region in us-east-1 us-east-2 eu-west-1; do timeout 3 python3 -c "import psycopg2; psycopg2.connect('postgresql://postgres.[REF]:pw@aws-0-${region}.pooler.supabase.com:6543/postgres?sslmode=require', connect_timeout=3)" 2>&1 | head -1 doneIf ALL return "tenant not found" (not timeout), the pooler isn't provisioned. Fix: go to Supabase Dashboard → Database → check if "Connection pooling" section exists. If not, the pooler may need to be enabled or the project needs time.
-
Diagnosing DB connectivity from Vercel: When the homepage times out but static pages work, it's almost certainly a DB connection issue. Quick diagnostic sequence:
- Check if Supabase REST API responds:
curl -s -o /dev/null -w "%{http_code}" https://[project].supabase.co/rest/v1/(401 = project alive, 503 = paused) - Check pooler port:
nc -zv aws-0-us-east-2.pooler.supabase.com 6543 - Verify connection string locally:
python3 -c "import psycopg2; psycopg2.connect('[DATABASE_URL]', connect_timeout=5)" - Check Vercel logs:
vercel logs --environment production --level error --limit 10
- Check if Supabase REST API responds:
-
Supabase credential confusion — multiple key formats exist. The Supabase dashboard and API show several different credential types that are easy to confuse:
Key Type Format Used For anon(JWT)eyJhbG...Client-side PostgREST service_role(JWT)eyJhbG...Admin PostgREST, DB access publishablesb_publishable_...Supabase Management API secretsb_secret_...Supabase Management API Legacy JWT secret Base64 string Token signing verification For Django DATABASE_URL, only the PostgreSQL connection string matters (from Settings → Database → Connection string tab). The JWT keys are for PostgREST/REST API, NOT for direct DB connections.
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=Falsein production
04 同仓库更多 Skills
web-ui-verification
Verify web UIs via headless Chrome CDP, no vision needed.
test-driven-development
TDD: enforce RED-GREEN-REFACTOR, tests before code.
systematic-debugging
4-phase root cause debugging: understand bugs before fixing.
spike
Throwaway experiments to validate an idea before build.
simplify-code
Parallel 4-agent cleanup of recent code changes.
scroll-driven-3d-websites
Scroll-scrubbed 3D promo sites (Three.js + GSAP).