Skip to lesson content

PROJECT 8 · LESSON 16 OF 16

Deploy the store live and verify a release

Publish on Render, configure PostgreSQL and HTTPS, and prove the deployed application works.

  • release steps
  • health checks
  • custom domains
  • backups
  • smoke tests

Your workspace: edushop

Continue from lesson 15: Prepare the application for production. Keep existing files; create or replace the complete files listed below.

Extract the ZIP and open the folder containing manage.py. Create a Python virtual environment, install requirements.txt and run migrate. Read README.md for checkpoint-specific commands and LESSON.md for offline explanations. Checkpoints contain no database records or private credentials.

1. Understand the problem and the concepts

Why we need this feature

Deployment is complete when another person can use the public HTTPS address and their data survives a redeploy. This final project connects hosting, database migrations, domains, smoke checks and recovery into one reproducible release procedure.

This lesson provides an executable deployment path for your own Django application. Publishing these notes on EduPoly does not create a hosting account or deploy a student store automatically. Hosting plans and domain registration can cost money; inspect current provider terms before provisioning.

Follow RELEASE.md in order. Its final verification is functional: a public HTTPS URL, working forms and static assets, a persisted order, protected customer data, and a tested redeploy.

Prepare an artifact and services you control

Use the final checkpoint as the application source, not the EduPoly website repository. Place manage.py, requirements.txt and build.sh at the repository root, or configure the hosting root directory to their containing folder. Commit source and migration files; exclude .venv, db.sqlite3, secrets and collected output according to .gitignore.

On Render create a persistent PostgreSQL database and a Python web service from your repository, preferably in the same region. Choose plans that support the shell, pre-deploy command, database retention and backups you need; availability and charges can change. The tutorial supplies the deployment procedure, not a provisioned hosting account or paid service. Read RELEASE.md below before creating resources.

Build, migrate and start are distinct phases

The build command bash build.sh installs dependencies and collects static assets. The pre-deploy command python manage.py migrate --noinput applies schema changes once per release. The start command launches Gunicorn and binds the host-provided PORT. Keep migrations out of every web-worker startup; multiple workers should not independently race to change the schema.

Set DJANGO_DEBUG=0, a generated DJANGO_SECRET_KEY, DATABASE_URL, DJANGO_ALLOWED_HOSTS, DJANGO_CSRF_TRUSTED_ORIGINS and TRUST_PROXY=1 as documented. Set the supported Python runtime version in the host configuration. Use the database’s suitable internal connection URL for the web service and keep credentials out of screenshots and Git history.

After the service starts, use its shell to run createsuperuser and seed_products. The public database begins separately from your local one. Do not expect the local admin password or products to appear automatically. Keep seed execution intentional; its get_or_create behavior preserves edits but it still inserts demonstration records.

Verify behavior beyond the green deployment badge

Configure /health/ as the health endpoint. It performs a small database query and returns a generic failure if the database is unavailable, without exposing credentials or exceptions. A health response proves basic reachability, not that every customer workflow works.

Follow the live smoke test: load styled pages; register and log in; create and edit a private task; add and update a cart; place a cash-on-delivery order; inspect history; verify another account cannot open it; fulfill it as staff. Redeploy and confirm the records remain. Then test two independent buyers competing for the final stock unit on staging PostgreSQL. Only one should succeed.

A live application needs a recovery path

Add a custom domain using the hosting dashboard’s exact DNS instructions, then update allowed hosts and CSRF origins for the domain. Wait for DNS and TLS provisioning and repeat POST checks on the final HTTPS address. A working temporary hostname does not prove the custom origin is configured.

Enable database backups and practice restoring one into an isolated database. Rolling back application code does not automatically undo a migration or restore deleted records. Prefer backward-compatible schema changes and plan data changes before release. Read logs for errors without printing secrets or personal delivery data.

This is a complete instructional cash-on-delivery store with a limited fulfillment workflow. Before real customers, add your actual shipping/tax policies, customer support and recovery email, abuse controls, privacy/retention policy, and any required payment integration. Real online payments need verified server-side provider events and reconciliation; a redirect that says success is not proof of payment.

2. Follow the execution flow

Read this sequence before the source. Identify the input, the component or function that handles it, and the result the learner sees.

  1. Push the final application source to your own repository.

  2. Create PostgreSQL and the web service, then set the documented environment and commands.

  3. The build creates static output; the pre-deploy step applies migrations.

  4. Gunicorn starts and the host checks /health/ over its service network.

  5. Initialize staff and catalog data, then verify customer and staff flows through the public HTTPS URL.

  6. Redeploy, verify persistence, configure the custom domain and rehearse backup recovery.

Your release acceptance record

  1. Record the deployment commit and public HTTPS URL.
  2. Create a test order and note its ID, total and stock effect. Redeploy the same application and confirm the order still exists.
  3. Record the privacy, CSRF, static assets and staging concurrency checks. If a check fails, fix that specific dependency before calling the release complete.

3. Build it, one file at a time

  1. Commit the final source to your own Git repository. Create a persistent PostgreSQL service and Python web service on Render in the same region. Choose a plan supporting a release/pre-deploy command and shell access.
  2. Set Build Command to bash build.sh, Pre-deploy Command to python manage.py migrate --noinput, Start Command to gunicorn config.wsgi:application --bind 0.0.0.0:$PORT, and Health Check Path to /health/. Set a current Python 3.13 patch runtime in the provider configuration.
  3. Set the six environment variables described in RELEASE.md. Use your assigned Render hostname and HTTPS origin, not the example placeholders. Deploy and inspect each phase’s logs.
  4. Use the hosting shell to create the intended administrator and seed learning products. Open the public HTTPS URL in a private browser and complete the smoke checks below.
  5. Redeploy unchanged source and confirm orders survive. Rehearse backup restoration into a separate database; then follow the custom-domain and future-release instructions if needed.
Terminal
# Local source-control preparation (create your own remote repository first)
git init
git add .
git commit -m "Build Django learning store"
# Add your own repository URL, then push your chosen branch.

# Hosting shell, after migrations succeed
python manage.py createsuperuser
python manage.py seed_products
python manage.py check --deploy

The paths below are relative to your practice project. Each block is the complete file at this checkpoint. Read its responsibility first, type or copy the code, then use the walkthrough to explain the important statements.

shop/health.py

Provide a small readiness endpoint that checks the database connection.

shop/health.py
from django.db import connection
from django.http import JsonResponse


def health(request):
    try:
        with connection.cursor() as cursor:
            cursor.execute("SELECT 1")
    except Exception:
        return JsonResponse({"status": "unavailable"}, status=503)
    return JsonResponse({"status": "ok"})

Read the code

  1. SELECT 1 verifies connectivity without reading customer data. Failures return a generic 503 and do not reveal credentials.
  2. A 200 readiness check is necessary but not sufficient: application smoke tests still verify sessions, schema, writes and static assets.

config/urls.py

Expose the health endpoint alongside the completed application routes.

config/urls.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import include, path
from shop.accounts import signup
from shop.health import health

urlpatterns = [
    path("health/", health, name="health"),
    path("admin/", admin.site.urls),
    path("accounts/signup/", signup, name="signup"),
    path("accounts/login/", auth_views.LoginView.as_view(), name="login"),
    path("accounts/logout/", auth_views.LogoutView.as_view(), name="logout"),
    path("orders/", include("orders.urls")),
    path("tasks/", include("tasks.urls")),
    path("", include("shop.urls")),
]

Read the code

  1. The health route is independent of customer login so the hosting service can probe it.

RELEASE.md

Provide the full deployment and ongoing-release runbook with exact commands.

RELEASE.md
# Release EduShop to Render

1. Put the final checkpoint source in your own Git repository. Exclude .venv,
   .env, db.sqlite3 and staticfiles. Commit requirements and every migration.
2. Create a persistent Render PostgreSQL database. Choose a plan with the
   retention, backups and availability you need; do not assume a free tier is
   durable or that its limits stay unchanged. Keep its credentials private.
3. Create a Python web service from your repository in the same region.
   Set the root directory to the folder containing manage.py (blank if it is
   at repository root). Set Python to a current supported 3.13 patch release.
4. Build command: bash build.sh
   Pre-deploy command: python manage.py migrate --noinput
   Start command: gunicorn config.wsgi:application --bind 0.0.0.0:$PORT
   Health check path: /health/
   Choose a service plan that supports the pre-deploy command and shell access.
5. Set DJANGO_DEBUG=0, a generated DJANGO_SECRET_KEY, DATABASE_URL to the
   database's internal connection URL, DJANGO_ALLOWED_HOSTS to your assigned
   hostname (no scheme), DJANGO_CSRF_TRUSTED_ORIGINS to its https:// origin,
   and TRUST_PROXY=1 for this trusted Render proxy setup. Preserve the secret
   across normal deploys. Use the URL/TLS settings the database service requires.
6. Deploy. Inspect build, migration and startup logs separately. Do not skip a
   failed migration. A healthy root page does not prove checkout can write.
7. In the authenticated hosting shell run:
      python manage.py createsuperuser
      python manage.py seed_products
   Create only your intended staff account; never put an admin password in a
   build command or commit. Seed only a learning store; replace demo inventory
   before accepting real orders.
8. Open the HTTPS public URL in a signed-out/private browser. Verify CSS,
   product pages, signup, login, cart, checkout and owner-only order history.
   Confirm logout is POST and /admin/ rejects normal customers.
9. Check persistence: place a synthetic COD order, redeploy unchanged source,
   and confirm the order and stock remain. A new deployment must use the same
   persistent database. Confirm backups exist and rehearse restoration into
   a separate learning database.
10. Test the last unit with two isolated customers on PostgreSQL. At most one
    order can acquire it. Retry the same successful checkout token and confirm
    one order and one deduction. A failed multi-line order must leave all stock
    unchanged. Do not claim SQLite alone verifies concurrent row locking.
11. For a custom domain, add it in Render, configure the DNS records Render
    supplies at your registrar, wait for certificate issuance, and add that
    exact hostname/origin to ALLOWED_HOSTS/CSRF_TRUSTED_ORIGINS. Verify HTTPS
    before sending customer traffic. Keep the original hostname only if needed.
12. For future changes, test on a staging database, back up production, commit
    migrations, and deploy. Prefer backward-compatible schema changes. Rolling
    back application code does not automatically undo database migrations.

The included store supports cash on delivery, not online payment processing.
Before operating publicly, configure your delivery area, price/tax rules,
privacy/retention policy, support and order cancellation procedure. Add login
rate limiting at your edge or through a maintained integration and verified
email/recovery flows before onboarding real customers. No user-upload feature
is included; if added later, store uploads in persistent object storage, not
WhiteNoise's generated static directory.

Read the code

  1. Separate build, schema migration and web startup so a failure can be diagnosed at the correct stage.
  2. Provision persistent storage and use environment configuration rather than baking credentials into the repository.
  3. Verify a deployed customer journey and a redeploy. A successful build alone does not prove the store is operational.

4. Run it and check your result

  • The assigned HTTPS URL shows styled pages with DEBUG off.
  • /health/ returns status ok; signup, login, cart and COD checkout work on the deployed database.
  • Customer B cannot view customer A’s order URL. Staff can mark the order shipped.
  • A redeploy retains orders and stock; backup/restore is rehearsed separately.

5. Predict, change and observe

Redeploy after creating a product and an order in the hosted database.

Compare your prediction with the expected result

What you should observe

The records remain available after the web service is replaced.

Why it happens

Persistent PostgreSQL is independent of the web-service filesystem. Persistence across replacement is part of the deployment contract.

6. Troubleshoot with evidence

A common mistake

If login POST fails only on hosting, compare the exact HTTPS origin with trusted origins and proxy settings. Never disable CSRF as a workaround.

Service fails to bind or never becomes healthy

Likely cause: The start command ignores PORT, starts the development server or points at the wrong module.

Check and correct: Use the supplied Gunicorn command from RELEASE.md and verify the repository root contains config/wsgi.py.

Live site has no products or admin login

Likely cause: The hosted database is new.

Check and correct: Run migrate, createsuperuser and seed_products in the hosted environment; do not copy a local SQLite file into the service.

7. Practice and explain it back

Your independent task

Deploy a staging copy with its own database and hostname, then rehearse a harmless product-description release before changing the live application.

Attempt these questions before opening the explanations. Use the source above to justify your answer.

Why is a successful build insufficient?

Build validates packaging. Runtime configuration, database access, permissions, HTTPS forms and persistence are separate behaviors that need live checks.

Does redeploying old code restore old data?

No. Code and database state have different lifecycles. Backups and deliberate migration recovery are required for data restoration.