logo

AboutWorkCustomer StoriesContactBlogGithub
How to Deploy a Django App to Vercel
05 Dec 2024

How to Deploy a Django App to Vercel

DevOpsDjangoWeb Development

Discover a step-by-step guide to deploying your Django app on Vercel, from setup to configuration, enabling seamless hosting with lightning-fast performance and scalability for modern web applications.

Introduction

Deploying a Django app to Vercel can transform your project into a live, production-ready application. Vercel, known for its seamless deployments and powerful integrations, is an excellent choice for hosting Django apps. In this guide, we’ll walk through every step, from setting up your Django project for deployment to going live on Vercel.

By the end of this guide, you’ll have a Django app running on Vercel, complete with serverless functions and a fast, scalable setup.

Prerequisites

Before we dive in, ensure you have the following:
  • A Django application.
  • Python installed on your machine.
  • Git installed and configured.
  • A Vercel account. You can sign up here.

Step 1: Prepare Your Django App for Deployment

1.1 Configure the settings.py

Ensure your Django app is production-ready by updating some key settings.

1. Set Debug to False
In your `settings.py`, set `DEBUG` to `False` for production. This ensures sensitive information is not exposed.
DEBUG = False
2. Add Allowed Hosts
Include the domain or hostname that Vercel will use to serve your app.
ALLOWED_HOSTS = ['your-vercel-domain.vercel.app', '.vercel.app']
3. Static Files Configuration
Use Django's Whitenoise library to serve static files effectively in production. Install Whitenoise
pip install whitenoise
Update the MIDDLEWARE in your settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',  # Add this middleware
    ...
]
4. Database Configuration

When using a database like PostgreSQL, it’s a best practice to manage confidential and configurable variables through environment variables. This approach enhances security and simplifies configuration across different environments (e.g., development, staging, production). You can also use environment variables for other sensitive settings like SECRET_KEY, DEBUG, and ALLOWED_HOSTS.

To manage environment variables in your Django project, install the python-dotenv library:
pip install python-dotenv
Update your DATABASES settings:
from urllib.parse import urlparse
from dotenv import load_dotenv
load_dotenv()

POSTGRES_URL = urlparse(os.getenv("DATABASE_URL")) # for database url string


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': POSTGRES_URL.path.replace('/', ''),
        'USER': POSTGRES_URL.username,
        'PASSWORD': POSTGRES_URL.password,
        'HOST': POSTGRES_URL.hostname,
        'PORT': 5432,
    }
}

1.2 Configure wsgi.py

When deploying a Django application to Vercel, it uses Gunicorn as the WSGI server. To ensure your app works correctly, update your wsgi.py file to expose the WSGI application object as app.
Locate the wsgi.py file in the main application directory of your Django project (e.g., project/project/wsgi.py) and modify it as follows:
# project/project/wsgi.py

# Expose the WSGI application object for Vercel
app = application

1.3 Add a build.sh file

To automate the build process for your Django project during deployment, create a build.sh file in the root of your project directory. This script ensures your environment is set up correctly and your Django app is ready for production.
#!/bin/bash

# Build the project
echo "Building the project..."
python3.12 -m venv venv
source venv/bin/activate
python3.12 -m pip install -r requirements.txt

echo "Make Migration..."
python3.12 manage.py makemigrations --noinput
python3.12 manage.py migrate --noinput

echo "Collect Static..."
python3.12 manage.py collectstatic --noinput --clear

1.4 Create a requirements.txt

Generate a requirements.txt file listing all your project dependencies. Run the following command:
pip freeze > requirements.txt

1.5 Add a vercel.json File

To configure Vercel for deploying your Django project, create a vercel.json file in the root directory of your project. This file defines deployment regions, build settings, and routing rules.

Create the vercel.json File

Add the following content to your vercel.json file:

{
    "regions": ["sin1"],
    "builds": [
        {
            "src": "project_name/wsgi.py",
            "use": "@vercel/python",
            "config": { "maxLambdaSize": "15mb", "runtime": "python3.12" }
        },
        {
            "src": "build.sh",
            "use": "@vercel/static-build",
            "config": {
                "distDir": "./staticfiles"
            }
        }
    ],
    "routes": [
        {
            "src": "/(.*)",
            "dest": "project_name/wsgi.py"
        }
    ]
}

Explanation of Configuration

  1. regions:
    Specifies the Vercel region to deploy to.

    • "sin1": Deploys to the Singapore region. You can change this to another region (e.g., "iad1" for Virginia, USA) based on your audience's location.
  2. builds:
    Defines the build steps for your project:

    • WSGI App:
      • "src": "project_name/wsgi.py": Points to the wsgi.py file of your Django project. Replace project_name with your actual project folder name.
      • "use": "@vercel/python": Specifies the Python runtime environment for the WSGI app.
      • "config":
        • "maxLambdaSize": "15mb": Adjusts the size limit for the serverless function.
        • "runtime": "python3.12": Uses Python 3.12 runtime.
    • Static Build:
      • "src": "build.sh": Points to the build.sh file to automate migrations, static file collection, etc.
      • "use": "@vercel/static-build": Specifies the static build process.
      • "distDir": "./staticfiles": Points to the directory containing your static files after collection.
  3. routes:
    Maps all incoming routes to your Django WSGI app:

    • "src": "/(.*)": Matches all URLs.
    • "dest": "project_name/wsgi.py": Routes them to the wsgi.py file.
Some outdated tutorials include a version option in vercel.json, but this option has been deprecated and should no longer be used.

Step 2: Push Your Project to GitHub

Vercel uses Git for deployments. Push your project to GitHub (or any Git provider supported by Vercel).

1. Initialize a Git repository if you haven’t already:

git init

2. Commit your changes:

git add .
git commit -m "Prepare Django app for deployment"

3. Add your GitHub remote repository and push your code:

git remote add origin <your-repo-url>
git branch -M main
git push -u origin main

Step 3: Deploy to Vercel

3.1 Connect Your Repository

  1. Go to Vercel's dashboard.
  2. Click on "Add New Project."
  3. Select "Import Git Repository."
  4. Choose the repository you just pushed.
article content image

3.2 Configure Deployment Settings

1. Set the Framework Preset

In the Build and Output Settings section of your deployment platform (e.g., Vercel), set the Framework Preset to Other. This is necessary because Django is not one of the predefined frameworks.

2. Add Environment Variables

Add the required environment variables to your deployment settings. These variables ensure your application has access to sensitive configuration values and resources like the database. Here's an example of environment variables you might need:
SECRET_KEY="zx3gZ6Some^Pl964oQp@pvC%aiaAxqo7theeFgjYk^mjgpnPekzWxof6VF#nAhZD9"
ALLOWED_HOSTS="localhost,127.0.0.1,portfoliofy-sigma.vercel.app,.vercel.app"
DATABASE_URL='postgresql://neondb_owner:something-aws.neon.tech/neondb?sslmode=require'

# And other environment variables you have congigured

3.3 Deploy Your Project

After completing all the configuration steps, you're ready to deploy your Django project. Simply click the Deploy button on your hosting platform to start the deployment process.Once the deployment is complete, you’ll receive a URL where your application is live. Make sure to test the deployed application to verify that all functionalities, including database connections, static files, and environment-specific settings, are working as expected.

Final Conclusion

Congratulations! 🎉 You’ve successfully deployed your Django project. Here’s a summary of what we’ve accomplished:

  1. Configured WSGI and Build Processes: Ensured the project is compatible with the hosting platform using wsgi.py and build.sh.
  2. Environment Variables: Secured sensitive settings like SECRET_KEY and database credentials using environment variables.
  3. Deployment Configuration: Set up platform-specific settings, including routes and build outputs via vercel.json.
  4. Final Deployment: Deployed the project to your hosting platform, making it live and accessible to users.

By following these steps, you’ve established a secure, efficient, and scalable foundation for your Django application in a production environment.For further improvements, consider:

  • Adding logging and monitoring tools to track performance and issues.
  • Optimizing database and query performance as your application scales.

Your project is now ready to serve your audience! 🚀

Similar Posts

Fetching data in React Native
Mobile DevelopmentReactWeb Development

Fetching data in React Native

Learn how to fetch data in React Native using both the native fetch API and the powerful TanStack Query. Explore advanced usage, error handling, caching, and more with code examples for both approaches.

05 Dec 2024

5 min read

iptables: the Art of Breaking Your Network Before Fixing It
DevOpsLinux

iptables: the Art of Breaking Your Network Before Fixing It

Learn how to master iptables, from the basics to advanced setups, while probably locking yourself out a few times. Firewalls have never been this exciting or frustrating

05 Dec 2024

5 min read

Linux Superpowers: Mastering Advanced Commands for Every SysAdmin
DevOpsLinux

Linux Superpowers: Mastering Advanced Commands for Every SysAdmin

Discover advanced Linux commands and their powerful usage. Learn how to leverage tools like find, grep, sed, and awk for efficient system management, data manipulation, and text processing

25 Nov 2024

5 min read

Stay curious. Stay inspired. Let the stories find you.

Subscribe to get fresh insights, coding tips, and the latest in tech delivered straight to your inbox. Whether you're a beginner or an expert, there's always something new to explore. Be the first to explore stories that inspire, inform, and ignite your imagination