DEV Community

Cover image for How to Deploy a Django REST API on Render for Free
Sospeter Mong'are
Sospeter Mong'are

Posted on

How to Deploy a Django REST API on Render for Free

Deploying a Django REST API to Render is an excellent way to host your application in the cloud. Render offers a developer-friendly platform with a generous free tier, making it perfect for hosting small projects or testing applications. This guide will walk you through deploying your Django REST API to Render for free, covering everything from prerequisites to connecting your PostgreSQL database.


Introduction

Deploying a Django REST API involves hosting your backend code, database, and static files in a way that is accessible over the web. Render simplifies this process by providing a managed hosting environment that integrates with GitHub/GitLab repositories, supports PostgreSQL databases, and automates deployment. By the end of this tutorial, your Django REST API will be live on a public URL, ready to serve requests.


Prerequisites

Before you begin, ensure you have the following:

  1. A Django REST API project ready for deployment.
  2. A GitHub or GitLab account with your project pushed to a repository.
  3. Basic knowledge of Django settings and environment variables.
  4. Python and Django installed locally.
  5. An account on Render

Step 1: Prepare Your Django Project for Deployment

  1. Install Deployment Dependencies: Ensure your project has the necessary libraries for production:
   pip install gunicorn psycopg2-binary whitenoise dj-database-url
Enter fullscreen mode Exit fullscreen mode
  1. Update settings.py: Modify the configuration to support Render's environment. Based on the snippet provided:
   import os
   import dj_database_url

   DEBUG = os.environ.get("DEBUG", "False").lower() == "true"

   # Allowed hosts
   ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(' ') if not DEBUG else []

   # Database configuration
   DATABASES = {
       'default': dj_database_url.parse(os.environ.get('DATABASE_URL', ''))
   }

   # Static files configuration
   STATIC_URL = '/static/'
   STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
   MIDDLEWARE = [
       'django.middleware.security.SecurityMiddleware',
       'whitenoise.middleware.WhiteNoiseMiddleware',
   ] + MIDDLEWARE
Enter fullscreen mode Exit fullscreen mode
  1. Create a requirements.txt File: Ensure your project dependencies are listed:
   pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode
  1. Create a Procfile: Define the command to run your application:
   web: gunicorn myproject.wsgi --log-file -
Enter fullscreen mode Exit fullscreen mode

Replace myproject with the name of your Django project.


Step 2: Set Up a PostgreSQL Database

Render provides managed PostgreSQL databases on its free tier. Follow these steps to set up your database:

  1. Create a New PostgreSQL Database:

Create new PostreSQL

  • Name your database,and leave the rest of the credentials to be autogenerated and select the Free Tier.

Name your database

Free tier

  1. Note Your Database Credentials: After creation, Render will provide the DATABASE_URL. Copy this value(External Database URL); you'll use it in your Django settings.

Database credentials


Step 3: Connect Your Database

  1. Update Your .env File (Optional): Store your database URL securely:
   DATABASE_URL=postgresql://<username>:<password>@<host>:<port>/<dbname>
Enter fullscreen mode Exit fullscreen mode
  1. Update settings.py: If not done earlier, configure Django to use the database URL:
   DATABASES = {
       'default': dj_database_url.parse(os.environ.get('DATABASE_URL'))
   }
Enter fullscreen mode Exit fullscreen mode
  1. Apply Migrations: Test your database connection locally by running migrations:
   python manage.py makemigrations
   python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Create a Web Service on Render

  1. Push Your Code to GitHub/GitLab: Ensure your project is committed and pushed to a GitHub or GitLab repository:
   git add .
   git commit -m "Prepare project for Render deployment"
   git push origin main
Enter fullscreen mode Exit fullscreen mode
  1. Create a New Web Service:

    • In the Render dashboard, click New + > Web Service.
    • Select your repository and branch.
  2. Configure the Service:

    • Build Command:
     pip install -r requirements.txt
     python manage.py collectstatic --noinput
     python manage.py migrate
    
  • Start Command:

     gunicorn myproject.wsgi
    

    Replace myproject with your project name.

Web service settings

  1. Set Environment Variables: Add the following environment variables in Render:
    • DEBUG = False
    • DATABASE_URL = (The External URL from your PostgreSQL setup)
    • ALLOWED_HOSTS = (e.g., your-app.onrender.com). You will find this at the top-left corner when you open the created web service

Environment variables

  1. Deploy the Service: Render will build and deploy your app automatically. Once complete, you’ll get a live URL.

Deployment successfully


Step 5: Test Your Deployment

Visit the public URL provided by Render (e.g., https://your-app.onrender.com) and verify that your Django REST API is working.

Additional Tips

  • Custom Domain: You can link a custom domain to your Render app through the dashboard.
  • Static Files: If you encounter issues, double-check your STATIC_URL and STATIC_ROOT settings.
  • Logs: Use Render’s log viewer to debug any deployment issues.

Deploying your Django REST API on Render is an efficient and cost-effective solution for hosting your backend. With its free tier, Render provides a perfect opportunity to deploy and test your projects without financial commitment. Follow this guide, and your Django REST API will be live in no time!

Incase you get stuck, You can reach out to me on X(formerly Twitter)

Happy coding !

Top comments (3)

Collapse
 
wathikaeng profile image
wathika • Edited

I recommend using neon.tech for your PostgreSQL database, as they allow up to 10 instances for free.
Additionally, set up cron jobs to keep your API active on Render, as it goes inactive after 90 seconds of inactivity.

Collapse
 
msnmongare profile image
Sospeter Mong'are

Thank you @wathikaeng for sharing this, I will try neon.tech

Collapse
 
arnav1333 profile image
Arnav Pawar

Thanks! I was struggling with the deployment for months but now i have successfully deployed my first Django REST API. Helpful!!