# Deploy a Django app with Postgres and Render Workflows using Claude Code

- Date: 2026-10-23T15:51:37.615Z
- URL: https://render.com/articles/deploy-a-django-app-with-postgres-and-render-workflows-using-claude-code

This tutorial shows how to use Claude Code's Render plugin to take an existing Django repo to a live deploy with Render Postgres and a Render Workflows task. Render's official skills let agents deploy, debug, and monitor your apps. Along the way, the agent tends to hit a predictable set of Django production problems. For each one, this tutorial gives you the prompt to send Claude Code and the fix it should produce.

For an overview of pricing and production options, see [Django hosting on Render](https://render.com/hosting/django).

The example app uses no Celery and no message broker. All background and long-running work goes through Render Workflows.

Here's the path:

1. Install the plugin.
2. Prompt the deploy.
3. Fix the Django pitfalls.
4. Add a Workflows task.
5. Validate the configuration.
6. Deploy.
7. Check the logs.

*Prerequisites:* an existing Django repo and a working Claude Code setup.

## Install the Render plugin in Claude Code

The official Render plugin for Claude Code bundles Render's skills and configures the Render MCP server (Model Context Protocol server) with OAuth automatically. The MCP server exposes platform actions to the agent.

To install, run these two commands in Claude Code:

```text
/plugin marketplace add render-oss/render-plugin-claude-code
/plugin install render
```

The first time Claude uses a Render MCP tool, you approve a browser prompt to connect with OAuth, and you don't need a Render API key. For the full setup, see [Render's Claude Code agent page](https://render.com/agents/claude). For more on the bundled skills, see the [agent skills and plugins docs](https://render.com/docs/llm-support).

## Prompt Claude Code to deploy

Give the agent a specific prompt that names the database and asks for a Blueprint file. Ask it to prepare the changes without deploying, so you can validate them first:

```text
Prepare this Django app for deployment to Render with a Render Postgres database.
Define the web service and the database in a render.yaml Blueprint,
and wire the database connection string into the web service's environment.
Don't deploy yet. I'll review the changes first.
```

You can include extra details such as environment variables or a branch, and you can fix anything you forget with a follow-up prompt.

The agent writes `render.yaml` as part of this step. The first draft usually looks something like the simplified skeleton below. Comments mark the lines the next section corrects.

```yaml pseudocode
# Simplified render.yaml skeleton. Adapt names, plans, and commands to your repo.
services:
  - type: web
    name: mysite
    runtime: python
    plan: 0.5c-512mb                           # Pitfall: pre-deploy needs a non-Free plan
    buildCommand: "./build.sh"                 # Pitfall: static files (collectstatic)
    startCommand: "gunicorn mysite.wsgi"       # Pitfall: PORT binding
    preDeployCommand: "python manage.py migrate"  # Pitfall: migrations
    envVars:
      - key: DATABASE_URL                      # Pitfall: DATABASE_URL wiring
        fromDatabase:
          name: mysite-db
          property: connectionString
      - key: SECRET_KEY                        # Pitfall: secrets and DEBUG
        generateValue: true

databases:
  - name: mysite-db
```

For the full field reference, see the [Blueprint spec](https://render.com/docs/blueprint-spec). Expect to make Django-specific corrections before this file is ready.

## Django pitfalls the agent hits

Each pitfall below follows the same pattern: the symptom, the prompt to give Claude Code, and the fix it should produce. For Gunicorn tuning and overall production topology, see Render's [Django deploy guide](https://render.com/docs/deploy-django).

### Gunicorn and PORT binding

*Symptom:* The deploy times out or reports no open ports, because Gunicorn isn't bound to `0.0.0.0` on the port Render expects.

Render expects your app to bind to `0.0.0.0`, optionally using the `PORT` environment variable to set a custom port (the default port is `10000`). Render forwards inbound traffic to only one HTTP port per web service.

```text
Update the startCommand in render.yaml so Gunicorn binds to 0.0.0.0 on the PORT environment variable.
```

The fix looks like this:

```yaml
startCommand: "gunicorn mysite.wsgi:application --bind 0.0.0.0:$PORT"
```

### Static files with collectstatic and WhiteNoise

*Symptom:* Pages load without CSS, and the Django admin is unstyled.

Django designed its built-in static file serving for development with `DEBUG` on, so you need another approach in production. [WhiteNoise](https://whitenoise.readthedocs.io/) serves collected static files from the web process, which means `collectstatic` has to run during the build.

```text
Add WhiteNoise to this project. Put its middleware directly after SecurityMiddleware,
set STATIC_ROOT, and run collectstatic in build.sh. Add whitenoise to requirements.txt.
```

A simplified version of the settings change looks like this:

```python
# settings.py (excerpt)
MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware",
    "whitenoise.middleware.WhiteNoiseMiddleware",  # directly after SecurityMiddleware
    # ...the rest of your middleware
]

STATIC_URL = "static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
```

The build script installs dependencies and collects static files:

```bash runnable
#!/usr/bin/env bash
# build.sh: minimal example. Make it executable with chmod +x build.sh
set -o errexit
pip install -r requirements.txt
python manage.py collectstatic --no-input
```

### ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS

*Symptom:* Requests fail with a `DisallowedHost` error once `DEBUG` is off. Admin logins and form posts fail CSRF verification.

Follow Render's Django guide and move secrets and debug settings out of the code first: read `SECRET_KEY` from an environment variable instead of storing it in source, and turn `DEBUG` off on Render by checking for the `RENDER` environment variable. A web service's hostname is its `onrender.com` hostname, such as `myapp.onrender.com`.

```text
In settings.py, read SECRET_KEY from the environment and set DEBUG = "RENDER" not in os.environ,
and add SECRET_KEY to the web service's envVars in render.yaml with generateValue: true.
Read RENDER_EXTERNAL_HOSTNAME and add it to ALLOWED_HOSTS.
Add its https:// origin to CSRF_TRUSTED_ORIGINS.
```

The fix should look something like this:

```python
# settings.py (excerpt)
import os

# Production: Render sets SECRET_KEY. The default is for local development only.
SECRET_KEY = os.environ.get("SECRET_KEY", default="dev-only-insecure-key")

# DEBUG is off whenever the app runs on Render.
DEBUG = "RENDER" not in os.environ

ALLOWED_HOSTS = []
CSRF_TRUSTED_ORIGINS = []

RENDER_EXTERNAL_HOSTNAME = os.environ.get("RENDER_EXTERNAL_HOSTNAME")
if RENDER_EXTERNAL_HOSTNAME:
    ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME)
    CSRF_TRUSTED_ORIGINS.append(f"https://{RENDER_EXTERNAL_HOSTNAME}")

# Custom domains: add each one to BOTH lists.
```

In `render.yaml`, let Render generate the key. With `generateValue: true`, Render sets a randomized, base64-encoded, 256-bit value:

```yaml
envVars:
  - key: SECRET_KEY
    generateValue: true
```

When you add a custom domain later, add it to both host settings. Otherwise the same errors return on the new hostname.

### DATABASE_URL wiring from Postgres

*Symptom:* The app silently uses SQLite or a `localhost` default, or it fails to connect to the database at startup.

Every Render Postgres database has an internal URL for services in the same region and an external URL for everything else. Use the internal URL wherever possible, because it keeps traffic on your private network.

```text
Wire DATABASE_URL from the Postgres instance's connection string in render.yaml,
and parse it in settings.py with dj-database-url. Fail loudly if DATABASE_URL
is missing instead of falling back to a local default. Add psycopg2-binary and
dj-database-url to requirements.txt.
```

The `render.yaml` side of the fix:

```yaml
envVars:
  - key: DATABASE_URL
    fromDatabase:
      name: mysite-db
      property: connectionString
```

The settings side of the fix fails at startup instead of quietly connecting to the wrong database:

```python
# settings.py (excerpt). For local development, set DATABASE_URL in your shell or .env.
import os

import dj_database_url
from django.core.exceptions import ImproperlyConfigured

if not os.environ.get("DATABASE_URL"):
    raise ImproperlyConfigured("DATABASE_URL isn't set. Check fromDatabase in render.yaml.")

DATABASES = {"default": dj_database_url.config(conn_max_age=600)}
```

### Migrations as a pre-deploy command

*Symptom:* Tables are missing after the first deploy. Alternatively, the agent puts `migrate` in `build.sh` or in front of Gunicorn in the start command.

When you set a pre-deploy command, Render runs it just before each deploy, which makes it a good fit for database migrations.

```text
Run python manage.py migrate as a pre-deploy command in render.yaml,
not in build.sh or the start command.
```

The fix:

```yaml
preDeployCommand: "python manage.py migrate"
```

If the pre-deploy command fails or runs longer than 30 minutes, the deploy fails and your service keeps running its most recent successful deploy. For details, see [Deploying on Render](https://render.com/docs/deploys).

> *Check plan availability first.* On a Free compute plan, Render's docs direct you to run database migrations in the build command instead. Put the web service on a paid compute plan, such as `0.5c-512mb` (the current plan ID for the legacy `starter` plan), before you rely on `preDeployCommand` for migrations, and set the `plan` field accordingly. See [Updates to Render Compute Plans](https://render.com/docs/compute-plans-update) for plan IDs and [Deploying on Render](https://render.com/docs/deploys) for pre-deploy command availability. Don't move `migrate` into the start command as a workaround. A start command runs on every instance start, so several instances can run migrations at the same time and race against each other.

## Run background work as a Render Workflows task

Suppose the example app has one long-running job: generating a monthly report. This example doesn't use Celery, a broker or a worker service. Define the job as a Render Workflows task instead, so all async work in this app goes through Workflows. A workflow service is a collection of tasks you define as code and register with Render. You write those tasks as Python functions using the Render SDK, in a Git repo that the workflow service pulls from. Each run executes in its own instance, which Render spins up on demand.

Name the skill explicitly in your prompt, and ask for every piece you need:

```text
Use the render-workflows skill to set up generate_monthly_report as a
Render Workflows task in a workflows/ directory of this repo. Add a
workflow service named mysite-workflows to render.yaml that runs
workflows/tasks.py, and set DATABASE_URL on it to mysite-db's internal connection string.
Add a Django helper and a management command that trigger the task with
the Render SDK, and tell me the task's slug.
```

The agent should add a workflow service like this under `services:` in `render.yaml`. A workflow in a Blueprint requires a `region`. Set it to the same region as `mysite-db`, because the internal connection string only works for services in the same region. If you don't set a region on the database, Render uses `oregon`. A workflow also requires `repo`. Unlike web services, the validator rejects a workflow missing `repo` ("repo is required for git-based services"), even when you validate from inside that repository, according to the [render-workflows skill](https://github.com/render-oss/skills/blob/HEAD/skills/render-workflows/SKILL.md). `branch` stays optional.

```yaml
# render.yaml (excerpt): add under services:
  - type: workflow
    name: mysite-workflows
    runtime: python
    region: oregon                 # Required for workflows. Match mysite-db's region.
    repo: https://github.com/your-org/mysite  # Required for workflows, even when validating inside this repo.
    buildCommand: pip install -r requirements.txt
    startCommand: python workflows/tasks.py
    envVars:
      - key: DATABASE_URL
        fromDatabase:
          name: mysite-db
          property: connectionString
```

Don't set `plan`, `previews`, or `preDeployCommand` on a workflow in a Blueprint. Workflows set compute per task in code, not on the service.

### The task module

This simplified example follows the Python SDK pattern from the [Render Workflows docs](https://render.com/docs/workflows):

```python
# workflows/tasks.py: simplified example of a task definition.
from render import TaskContext, Workflows

app = Workflows()


@app.task
def generate_monthly_report(ctx: TaskContext, account_id: int, month: str) -> dict:
    # Render passes ctx to every run automatically. Callers don't include it in the input.
    # Production: add logging and make the task idempotent so retries are safe.
    # Inputs arrive as arguments. Results go to Postgres via DATABASE_URL,
    # which you set on the workflow service.
    report = {"account_id": account_id, "month": month, "rows": 0}
    # ...build the report here...
    return {"status": "done", **report}


if __name__ == "__main__":
    app.start()  # SDK entry point
```

### The Django trigger

Install the Render SDK (`pip install render`) and add `render` to `requirements.txt`. Set `RENDER_API_KEY` in the Django service's environment, because the SDK client detects and uses that variable automatically. The Render SDK calls the Render API under the hood to trigger task runs.

A trigger helper keeps SDK calls in one place and handles failures. `start_task` starts the run and returns without waiting for it to finish (see [Triggering Task Runs](https://render.com/docs/workflows-running)).

```python
# reports/workflows.py: simplified trigger helper. Adapt to your app.
import logging
import os

from render import Render

logger = logging.getLogger(__name__)


def start_monthly_report(account_id: int, month: str):
    """Start a task run. Return the run, or None if the trigger fails."""
    # Read the slug at call time so a missing value returns None instead of raising at import.
    task_slug = os.environ.get("REPORT_TASK_SLUG")  # e.g. mysite-workflows/generate_monthly_report
    if not task_slug:
        logger.error("REPORT_TASK_SLUG isn't set")
        return None
    try:
        client = Render()  # Reads RENDER_API_KEY from the environment
        # Starts the run without waiting for it to finish.
        return client.workflows.start_task(task_slug, [account_id, month])
    except Exception:
        # Production: catch the SDK's specific error types and add retries.
        logger.exception("Failed to start task run for %s", task_slug)
        return None
```

A management command calls the helper, and a view can call it the same way:

```python
# reports/management/commands/run_monthly_report.py: minimal example.
from django.core.management.base import BaseCommand, CommandError

from reports.workflows import start_monthly_report


class Command(BaseCommand):
    help = "Start a generate_monthly_report task run."

    def add_arguments(self, parser):
        parser.add_argument("account_id", type=int)
        parser.add_argument("month")  # e.g. 2026-09

    def handle(self, *args, **opts):
        run = start_monthly_report(opts["account_id"], opts["month"])
        if run is None:
            raise CommandError("Task run didn't start. Check RENDER_API_KEY and REPORT_TASK_SLUG.")
        self.stdout.write(self.style.SUCCESS(f"Started task run: {run}"))
```

Add the key and slug to the web service in `render.yaml`. `sync: false` keeps the API key out of the file:

```yaml
envVars:
  - key: RENDER_API_KEY
    sync: false          # Set the value in the Dashboard, never in Git
  - key: REPORT_TASK_SLUG
    value: mysite-workflows/generate_monthly_report
```

By default, task runs time out after 2 hours, and you can raise the limit to up to 24 hours per task. See [Limits and Pricing for Render Workflows](https://render.com/docs/workflows-limits).

### Design limits

- *Scheduling:* Workflows has no native scheduling. Each run starts when your code calls the SDK or API. To run the report on a schedule, ask the agent to add a Render cron job that runs `python manage.py run_monthly_report` with the same `RENDER_API_KEY` and `REPORT_TASK_SLUG` as the web service. Also set `DATABASE_URL` on the cron job with `fromDatabase` and `property: connectionString`, because `settings.py` raises `ImproperlyConfigured` at startup when `DATABASE_URL` is missing. Each cron run can last up to 12 hours.
- *No incoming connections:* Task runs can't receive incoming connections. Pass everything a task needs as input arguments, and write results to Postgres instead of exposing an endpoint from the task.
- *Preview environments:* Preview environments don't support Render Workflows. If you enable previews for this Blueprint, Render skips creating a preview copy of `mysite-workflows`. See [Preview Environments](https://render.com/docs/preview-environments).

## Validate the generated configuration

Before you deploy, review the agent's changes against this checklist:

| Check | What to look for |
|---|---|
| Bind address | `--bind 0.0.0.0:$PORT` in `startCommand` |
| Static files | WhiteNoise after `SecurityMiddleware`, `STATIC_ROOT` set, `collectstatic` in `build.sh` |
| Hosts and CSRF | `RENDER_EXTERNAL_HOSTNAME` in `ALLOWED_HOSTS` and as an `https://` origin in `CSRF_TRUSTED_ORIGINS` |
| Secrets and debug | `SECRET_KEY` read from the environment (`generateValue: true` in `render.yaml`), and `DEBUG` off on Render|
| Database | `DATABASE_URL` uses `fromDatabase` with `connectionString`, parsed by `dj-database-url`, no local fallback |
| Migrations | `preDeployCommand: python manage.py migrate` with a paid `plan`, or `migrate` in `build.sh` on a Free compute plan, and never in `startCommand` |
| Workflow service | `type: workflow` in `render.yaml` with `region`, `repo`, `startCommand: python workflows/tasks.py`, and `DATABASE_URL` from `fromDatabase`|
| Workflow | Render SDK (`render`, 1.x) in `requirements.txt`, task takes `ctx: TaskContext` first |
| Schedule | If you added the cron job: cron job runs the trigger command with `RENDER_API_KEY`, `REPORT_TASK_SLUG`, and `DATABASE_URL` |

You can validate a Blueprint file with Render CLI v2.7.0 or later. The command exits with a non-zero status if the file fails validation:

```bash runnable
render blueprints validate render.yaml
```

Your IDE can also validate `render.yaml` live through SchemaStore.org. Then ask the agent to cross-check its own work:

```text
Validate render.yaml with the Render CLI, then check settings.py, build.sh,
the workflow task, and the trigger helper against this checklist. Report anything missing.
```

## Deploy through the agent

When validation passes, commit your changes and prompt the deploy:

```text
Deploy the validated render.yaml to Render. It creates the Postgres database,
the web service and the mysite-workflows workflow service.
```

If you added the scheduling cron job, it deploys with them. The agent determines the build configuration and deploys your services.

## Verify the deploy with logs

Ask the agent to read the logs and trigger one test run. Django settings still require `DATABASE_URL` at startup, so set it for the local run too. From your machine, use the database's external URL:

```text
Pull the latest deploy and service logs for mysite and summarize any errors.
Then run python manage.py run_monthly_report 42 2026-09 locally with
DATABASE_URL, RENDER_API_KEY, and REPORT_TASK_SLUG set, and confirm the task run appears.
```

A successful deploy shows these signs:

- The pre-deploy `migrate` command completed.
- Gunicorn logs that it's listening at `0.0.0.0` on your port.
- No `DisallowedHost` or CSRF errors appear.
- A triggered `generate_monthly_report` run appears for the workflow service.

If something's off, map the symptom back to its fix:

| Log symptom | Go back to |
|---|---|
| Port scan timeout, no open ports | Gunicorn and PORT binding |
| 404s on `/static/` paths, unstyled admin | Static files with collectstatic and WhiteNoise |
| `DisallowedHost`, `CSRF verification failed` | ALLOWED_HOSTS and CSRF_TRUSTED_ORIGINS |
| `ImproperlyConfigured: DATABASE_URL isn't set` | DATABASE_URL wiring from Postgres |
| `relation does not exist`, pre-deploy timeout | Migrations as a pre-deploy command |
| `Task run didn't start`, authentication errors from the SDK | The Django trigger |
| Task never registers in the workflow service | The task module |

## Where to go from here

- [Render's Django deploy guide](https://render.com/docs/deploy-django) for production topology
- [Render Workflows](https://render.com/docs/workflows) and [triggering task runs](https://render.com/docs/workflows-running)
- The [`pg create` CLI reference](https://render.com/docs/cli-reference)
- [Render's agents page](https://render.com/agents) for plugin setup

## Frequently asked questions

###### I'm on the Free plan. Do I have to give up pre-deploy migrations?

On a Free compute plan, Render's docs say to run database migrations in the build command. If you stay on Free, ask the agent to move `migrate` into `build.sh`. To keep `migrate` as a `preDeployCommand`, set the web service's `plan` to a paid compute plan such as `0.5c-512mb`.

###### Won't I miss having a worker service and queue for background jobs?

For this app, you don't need one. Each Workflows task run executes in its own instance that Render spins up on demand. Render also manages the task queue at no additional cost. That leaves you with no broker or worker process to deploy and monitor.

###### What if my report job might run longer than the default timeout?

Unless you change it, a task run times out after 2 hours. Ask the agent to raise the limit on that specific task, up to 24 hours. Leave other tasks at the default so a stuck run doesn't hold an instance longer than needed.

###### Can I trigger task runs from code that can't install the Python SDK?

Yes. Where the SDK isn't available, you can trigger runs by calling the Render API directly, for example with `curl`. The SDK itself uses the Render API under the hood. See [triggering task runs](https://render.com/docs/workflows-running) for details.

###### Is it safe to let Claude Code act on my Render account?

When you authenticate the MCP server, you grant your AI tool access to your workspaces and services, including potentially destructive operations such as modifying environment variables and triggering deploys. Make sure you're comfortable with that access before you connect it, and review the agent's changes before each deploy.

