Deploying Django with PostgreSQL on Vercel

Deploying Django with PostgreSQL on Vercel

Welcome to the world of web application deployment🚀 and my first blog 🤗!

In this blog, we will walk through the steps involved in deploying a Django application on Vercel, from start to finish. Whether you're a seasoned developer or just starting, this guide is for you.

Our goal is to make the deployment process as simple as possible, so you can focus on developing and improving your application.

Prerequisites

Created a Django Project. Refer to this article to create a Django project.

The plan

  1. Configure the project for Vercel

  2. Connect to database

  3. Deploy!

Configuring Django app

Step 1: In your project's root directory create a new file and name it build_files.sh then paste the code below inside it.

# build_files.sh
pip install -r requirements.txt

# make migrations
python3.9 manage.py migrate 
python3.9 manage.py collectstatic

Step 2: In your projects root directory create a new JSON file and name it vercel.json then paste the code below inside it and change the project name.

{
  "version": 2,
  "builds": [
    {
      "src": "projectname/wsgi.py",
      "use": "@vercel/python",
      "config": { "maxLambdaSize": "15mb", "runtime": "python3.9" }
    },
    {
      "src": "build_files.sh",
      "use": "@vercel/static-build",
      "config": {
        "distDir": "staticfiles_build"
      }
    }
  ],
  "routes": [
    {
      "src": "/static/(.*)",
      "dest": "/static/$1"
    },
    {
      "src": "/(.*)",
      "dest": "projectname/wsgi.py"
    }
  ]
}

"routes": [ ... ] rewrites all routes ("src": "/(.*)") to our WSGI application ("dest": "projectname/wsgi.py") to be handled.

Step 3: Go to your projects settings.py and paste in the code below

STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'),
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles_build', 'static')

Step 4: Create an empty folder and name it static in your project's root directory (this is where all our static files will be stored). Next, update your project's urls.py by importing👇

from django.conf import settings
from django.conf.urls.static import static

pasting in the configuration settings below after urlpatterns=[ ];

# add at the last
urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Step 5: Next step is to go to your settings.py file and update your ALLOWED_HOST to permit vercel.app to be a valid hostname for your Django app.

ALLOWED_HOSTS = ['.vercel.app', '.now.sh']
# Or * to allow all
ALLOWED_HOSTS = ['*']

Step 6: Go to your wsgi.py file created for you by Django in your project directory and append in the line of code below


import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saveplate.settings')
application = get_wsgi_application()
app = application #add here

Connecting to PostgreSQL

To use the database on your machine create a local PostgreSQL database. To connect our Django app that will be hosted on Vercel we need to host our database on a remote server. We can use Supabase to host the database.

Configure your Django app for connecting to PostgreSQL

Step 1: Install the package to connect with PostgreSQL. Recommended downloading the binary package.

pip install psycopg2-binary
Update your settings.py file with the below-given code

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': os.environ.get("DB_NAME"),
        'USER': os.environ.get("DB_USER"),
        'PASSWORD': os.environ.get("DB_PASSWORD"),
        'HOST': os.environ.get("DB_HOST"),
        'PORT': os.environ.get("DB_PORT"),
    }
}

Step 2: To store the local database connection info create a .env file inside the main app folder app/.env

DB_NAME= dbname
DB_USER= dbusername
DB_PASSWORD= dbpassword
DB_HOST= dbhost
DB_PORT= dbport

Step 3: To load the environment variables in file settings.py

Install package pip install python-dotenv

# settings.py
from dotenv import load_dotenv
load_dotenv()

Step 4: Update requirements.txt

pip freeze > requirements.txt

💡When hosting a project it's recommended to store the secret keys as environment variables. Since we are deploying the project on Vercel we will add the environment variables there. So now let's tell git to ignore the local env file which has the DB configurations.

Step 5: Add the .env file in gitignore.

.env

Push your code on GitHub 🚀.

We are all set for Deployment 🔥

Create an account on Vercel and connect to your GitHub account.

Step 1: Import the project from GitHub

Step 2: Get the database information from supabase and add the environment variables. Name them as you named them in the settings.py file.

Click on Deploy.

Congratulations 🎉

Your project is up and running 🔥

Finishing up 👋

You can choose a different database just add the database details in the environment variables and everything will work fine 😁.

Let me know if this blog helped you. And I would love to hear about your experience of contributing to open source for the first time. I am active on Twitter and LinkedIn if you want to say Hello!