Introduction
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
- 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
1. Set Debug to False
In your `settings.py`, set `DEBUG` to `False` for production. This ensures sensitive information is not exposed.
DEBUG = False
Include the domain or hostname that Vercel will use to serve your app.
ALLOWED_HOSTS = ['your-vercel-domain.vercel.app', '.vercel.app']
Use Django's Whitenoise library to serve static files effectively in production. Install Whitenoise
pip install whitenoise
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', # Add this middleware ... ]
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.
pip install python-dotenv
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
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
#!/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
pip freeze > requirements.txt
1.5 Add a vercel.json File
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
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.
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.
- WSGI App:
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
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
- Go to Vercel's dashboard.
- Click on "Add New Project."
- Select "Import Git Repository."
- Choose the repository you just pushed.
3.2 Configure Deployment Settings
1. Set the Framework Preset
2. Add Environment Variables
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:
- Configured WSGI and Build Processes: Ensured the project is compatible with the hosting platform using wsgi.py and build.sh.
- Environment Variables: Secured sensitive settings like SECRET_KEY and database credentials using environment variables.
- Deployment Configuration: Set up platform-specific settings, including routes and build outputs via vercel.json.
- 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! 🚀