
Using Supabase as a Database with Django: A Complete Step-by-Step Guide
Using Supabase as a Database with Django: A Complete Step-by-Step Guide
Are you a Django developer tired of managing traditional databases? Imagine combining Django's powerful ORM and rapid development with Supabase's scalable PostgreSQL, built-in authentication, realtime subscriptions, and edge functions—all without the hassle of server management. In this comprehensive guide, we'll walk you through using Supabase as your database backend for Django projects, from setup to production-ready tips.
Whether you're building a SaaS app, a realtime dashboard, or a blog with user interactions, this Supabase-Django combo unlocks modern features like Row Level Security (RLS) and instant APIs. Let's dive in!
What is Supabase?
Supabase is an open-source Firebase alternative built on PostgreSQL. It provides a full Backend-as-a-Service (BaaS) with:
- Postgres Database: Fully managed, with unlimited scaling.
- Authentication: JWT-based auth with social logins.
- Realtime: WebSocket subscriptions for live updates.
- Storage: For files and images.
- Edge Functions: Serverless JavaScript/TypeScript functions.
Since it's Postgres under the hood, it's a perfect match for Django, which has excellent PostgreSQL support via psycopg2 or psycopg.
Why Use Supabase with Django?
"Supabase supercharges Django by handling infra, security, and realtime out-of-the-box, letting you focus on code."
Key benefits:
- Zero DevOps: No need for AWS RDS or Heroku Postgres setup.
- Realtime Magic: Subscribe to DB changes without polling.
- Built-in Auth: Sync users seamlessly.
- Cost-Effective: Free tier for starters, pay-as-you-go scaling.
- SQL Familiarity: Write raw SQL or use Django ORM.
Prerequisites
Before we start:
- Python 3.8+ and Django 4.0+
- Supabase account (free at supabase.com)
- PostgreSQL knowledge (basic)
- Tools:
pip,git, virtualenv
Step 1: Setting Up Your Supabase Project
- Sign up at Supabase Dashboard and create a new project.
- Wait for the Postgres DB to initialize (2-3 minutes).
- Grab your connection details from Settings > Database:
- Host
- Port (usually 5432)
- Database name
- Username
- Password
- Test connection using Supabase's SQL Editor or
psql.
Pro Tip: Enable RLS on tables for security later.
Step 2: Configuring Django to Connect to Supabase PostgreSQL
Create a new Django project:
pip install django psycopg[binary]
django-admin startproject mysupabaseapp
cd mysupabaseapp
In mysupabaseapp/settings.py, update DATABASES:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'your_supabase_db_name',
'USER': 'postgres',
'PASSWORD': 'your_supabase_password',
'HOST': 'db.your-project-ref.supabase.co',
'PORT': '5432',
'OPTIONS': {
'sslmode': 'require', # Supabase requires SSL
},
}
}
Run python manage.py migrate to test the connection. Boom—Django is talking to Supabase!
Step 3: Defining Django Models and Running Migrations
Django's ORM shines here. Create an app:
python manage.py startapp core
In core/models.py:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Register in core/admin.py and run:
python manage.py makemigrations
python manage.py migrate
Check Supabase Dashboard > Table Editor—your core_post table is live!
Step 4: Integrating Supabase Authentication with Django
Supabase Auth is JWT-based. Install djangorestframework-simplejwt for API auth.
pip install djangorestframework-simplejwt supabase
Sync users by creating a Django model that mirrors Supabase's auth.users (read-only) or use custom user model.
For seamless integration:
- Enable Supabase Auth in Dashboard.
- Use Supabase JS client in frontend to get JWT.
- Validate JWT in Django middleware using
pyjwt.
Example middleware snippet:
import jwt
from django.http import JsonResponse
def supabase_jwt_middleware(get_response):
def middleware(request):
auth_header = request.META.get('HTTP_AUTHORIZATION')
if auth_header:
token = auth_header.split(' ')[1]
decoded = jwt.decode(token, options={"verify_signature": False}) # Verify with Supabase JWKS
request.user_id = decoded['sub']
response = get_response(request)
return response
return middleware
Step 5: Leveraging Realtime Features in Django
Supabase Realtime broadcasts DB changes. For Django (server-side), use realtime-py or Channels for WebSockets.
Install: pip install supabase channels
Listen to changes:
from supabase import create_client, Client
from asgiref.sync import sync_to_async
supabase: Client = create_client(supabase_url, supabase_key)
@sync_to_async
def listen_to_posts():
supabase.realtime.channel('db-changes').on(
'postgres_changes',
{'event': 'INSERT', 'schema': 'public', 'table': 'core_post'},
callback
).subscribe()
Best Practices and Security Considerations
- RLS + Policies: Enable in Supabase for user isolation.
- Connection Pooling: Use
pgbouncermode in Supabase for high traffic. - Environment Vars: Never hardcode creds—use
python-decouple. - Backups: Supabase handles daily PITR backups.
- Monitoring: Use Supabase Analytics + Django Debug Toolbar.
Conclusion: Build Faster with Supabase + Django
Integrating Supabase with Django is straightforward and powerful, blending Django's robustness with Supabase's modern features. Start prototyping today—your realtime, secure app awaits!
Have questions? Drop a comment below or check the Supabase Docs and Django Postgres Guide.
Ready to try? Fork this setup on GitHub: [Link to repo]