Building a SaaS Application with Django: Architecture, Auth, and Deployment

Django is one of the best frameworks for building Software-as-a-Service applications. Its built-in admin panel, ORM, authentication system, and vast ecosystem of packages make it ideal for SaaS products that need to move from prototype to production quickly. Companies like Instagram, Disqus, and Mozilla built their platforms on Django.
This tutorial walks you through the complete architecture of a Django SaaS application, from database design and multi-tenancy to authentication, subscription billing, and deployment. Whether you are building a SaaS product for the Nepali market or targeting international customers, these patterns will save you months of trial and error. At Swift Academy in Pokhara, our Django course covers these exact production patterns that employers and clients expect.
What Is the Best Architecture for a Django SaaS Application?
The best Django SaaS architecture uses a shared database with tenant isolation through foreign keys, separate Django apps for core modules like accounts, billing, and API, and a clear separation between tenant-specific and shared data.
Here is the recommended project structure:
saas_project/
├── config/
│ ├── __init__.py
│ ├── settings/
│ │ ├── base.py
│ │ ├── development.py
│ │ └── production.py
│ ├── urls.py
│ └── wsgi.py
├── apps/
│ ├── accounts/ # User management, authentication
│ ├── tenants/ # Organization/tenant management
│ ├── billing/ # Subscription and payment
│ ├── core/ # Shared utilities and base models
│ └── api/ # REST API endpoints
├── templates/
├── static/
├── manage.py
└── requirements.txt
Multi-Tenancy Approaches
| Approach | Description | Pros | Cons |
|---|---|---|---|
| Shared DB, shared schema | Tenant ID on every row | Simple, cost-effective | Requires careful query filtering |
| Shared DB, separate schemas | PostgreSQL schemas per tenant | Good isolation | Complex migrations |
| Separate databases | One database per tenant | Complete isolation | Expensive, hard to manage |
For most SaaS applications, the shared database with tenant isolation approach is the right choice. Here is the base model:
# apps/core/models.py
from django.db import models
from django.conf import settings
import uuid
class TenantModel(models.Model):
"""Base model for all tenant-specific data."""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
tenant = models.ForeignKey(
'tenants.Tenant',
on_delete=models.CASCADE,
related_name='%(class)s_items'
)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class TenantManager(models.Manager):
"""Manager that automatically filters by tenant."""
def for_tenant(self, tenant):
return self.filter(tenant=tenant)
class Tenant(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
owner = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
related_name='owned_tenants'
)
created_at = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
def __str__(self):
return self.name
How Do You Set Up Authentication and User Management?
Set up authentication using Django's built-in auth system extended with a custom user model, django-allauth for social login support, and role-based permissions tied to tenant membership for proper access control.
# apps/accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
import uuid
class User(AbstractUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(unique=True)
phone = models.CharField(max_length=15, blank=True)
avatar = models.ImageField(upload_to='avatars/', blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.email
class TenantMembership(models.Model):
"""Links users to tenants with roles."""
class Role(models.TextChoices):
OWNER = 'owner', 'Owner'
ADMIN = 'admin', 'Admin'
MEMBER = 'member', 'Member'
VIEWER = 'viewer', 'Viewer'
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='memberships')
tenant = models.ForeignKey('tenants.Tenant', on_delete=models.CASCADE, related_name='memberships')
role = models.CharField(max_length=20, choices=Role.choices, default=Role.MEMBER)
invited_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, related_name='invitations')
joined_at = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ('user', 'tenant')
def __str__(self):
return f"{self.user.email} - {self.tenant.name} ({self.role})"
Authentication Views with Django REST Framework
# apps/accounts/serializers.py
from rest_framework import serializers
from django.contrib.auth import authenticate
from .models import User, TenantMembership
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True, min_length=8)
tenant_name = serializers.CharField(write_only=True)
class Meta:
model = User
fields = ['email', 'username', 'password', 'tenant_name']
def create(self, validated_data):
tenant_name = validated_data.pop('tenant_name')
user = User.objects.create_user(**validated_data)
# Create tenant and membership
from apps.tenants.models import Tenant
tenant = Tenant.objects.create(
name=tenant_name,
slug=tenant_name.lower().replace(' ', '-'),
owner=user
)
TenantMembership.objects.create(
user=user,
tenant=tenant,
role=TenantMembership.Role.OWNER
)
return user
class LoginSerializer(serializers.Serializer):
email = serializers.EmailField()
password = serializers.CharField()
def validate(self, data):
user = authenticate(username=data['email'], password=data['password'])
if not user:
raise serializers.ValidationError("Invalid credentials")
if not user.is_active:
raise serializers.ValidationError("Account is disabled")
return {'user': user}
# apps/accounts/views.py
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import RegisterSerializer, LoginSerializer
@api_view(['POST'])
@permission_classes([AllowAny])
def register(request):
serializer = RegisterSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
tokens = RefreshToken.for_user(user)
return Response({
'user': {'email': user.email, 'username': user.username},
'tokens': {
'access': str(tokens.access_token),
'refresh': str(tokens),
}
}, status=status.HTTP_201_CREATED)
@api_view(['POST'])
@permission_classes([AllowAny])
def login(request):
serializer = LoginSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data['user']
tokens = RefreshToken.for_user(user)
return Response({
'user': {'email': user.email, 'username': user.username},
'tokens': {
'access': str(tokens.access_token),
'refresh': str(tokens),
}
})
How Do You Implement Subscription Billing in Django?
Implement subscription billing by creating plan and subscription models, integrating with payment gateways like Stripe or for Nepal-specific options like eSewa and Khalti, and using Django signals to handle subscription lifecycle events.
# apps/billing/models.py
from django.db import models
from apps.core.models import TenantModel
import uuid
class Plan(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
price_monthly = models.DecimalField(max_digits=10, decimal_places=2)
price_yearly = models.DecimalField(max_digits=10, decimal_places=2)
currency = models.CharField(max_length=3, default='USD')
# Feature limits
max_users = models.IntegerField(default=5)
max_projects = models.IntegerField(default=10)
max_storage_gb = models.IntegerField(default=5)
has_api_access = models.BooleanField(default=False)
has_priority_support = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
def __str__(self):
return f"{self.name} - ${self.price_monthly}/mo"
class Subscription(models.Model):
class Status(models.TextChoices):
ACTIVE = 'active', 'Active'
PAST_DUE = 'past_due', 'Past Due'
CANCELED = 'canceled', 'Canceled'
TRIALING = 'trialing', 'Trialing'
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
tenant = models.OneToOneField('tenants.Tenant', on_delete=models.CASCADE, related_name='subscription')
plan = models.ForeignKey(Plan, on_delete=models.PROTECT)
status = models.CharField(max_length=20, choices=Status.choices, default=Status.TRIALING)
current_period_start = models.DateTimeField()
current_period_end = models.DateTimeField()
cancel_at_period_end = models.BooleanField(default=False)
payment_gateway = models.CharField(max_length=20, default='stripe')
gateway_subscription_id = models.CharField(max_length=255, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def is_valid(self):
from django.utils import timezone
return (
self.status in [self.Status.ACTIVE, self.Status.TRIALING]
and self.current_period_end > timezone.now()
)
Middleware for Subscription Enforcement
# apps/billing/middleware.py
from django.http import JsonResponse
from apps.billing.models import Subscription
class SubscriptionMiddleware:
"""Enforce subscription status on API requests."""
EXEMPT_PATHS = ['/api/auth/', '/api/billing/webhook/', '/admin/']
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if any(request.path.startswith(p) for p in self.EXEMPT_PATHS):
return self.get_response(request)
if hasattr(request, 'tenant'):
try:
subscription = request.tenant.subscription
if not subscription.is_valid():
return JsonResponse(
{'error': 'Subscription expired. Please renew your plan.'},
status=402
)
except Subscription.DoesNotExist:
return JsonResponse(
{'error': 'No active subscription found.'},
status=402
)
return self.get_response(request)
For Nepali SaaS products, integrating with local payment gateways like eSewa and Khalti is essential since most of your users will not have international credit cards.
How Do You Build the REST API Layer?
Build the REST API layer using Django REST Framework with viewsets for CRUD operations, custom permissions that enforce tenant isolation, pagination for list endpoints, and filtering capabilities for a complete API experience.
# apps/api/permissions.py
from rest_framework.permissions import BasePermission
from apps.accounts.models import TenantMembership
class IsTenantMember(BasePermission):
"""Only allow access to tenant members."""
def has_permission(self, request, view):
tenant_id = request.headers.get('X-Tenant-ID')
if not tenant_id:
return False
return TenantMembership.objects.filter(
user=request.user,
tenant_id=tenant_id
).exists()
class IsTenantAdmin(BasePermission):
"""Only allow tenant admins and owners."""
def has_permission(self, request, view):
tenant_id = request.headers.get('X-Tenant-ID')
if not tenant_id:
return False
return TenantMembership.objects.filter(
user=request.user,
tenant_id=tenant_id,
role__in=['owner', 'admin']
).exists()
# apps/api/views.py
from rest_framework import viewsets, filters
from rest_framework.permissions import IsAuthenticated
from django_filters.rest_framework import DjangoFilterBackend
from .permissions import IsTenantMember
class TenantViewSet(viewsets.ModelViewSet):
"""Base viewset that automatically filters by tenant."""
permission_classes = [IsAuthenticated, IsTenantMember]
filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
def get_queryset(self):
tenant_id = self.request.headers.get('X-Tenant-ID')
return self.queryset.filter(tenant_id=tenant_id)
def perform_create(self, serializer):
tenant_id = self.request.headers.get('X-Tenant-ID')
serializer.save(tenant_id=tenant_id)
# Example: Project management viewset
class ProjectViewSet(TenantViewSet):
serializer_class = ProjectSerializer
queryset = Project.objects.all()
search_fields = ['name', 'description']
ordering_fields = ['created_at', 'name']
filterset_fields = ['status', 'priority']
# config/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from apps.api.views import ProjectViewSet
from apps.accounts.views import register, login
router = DefaultRouter()
router.register('projects', ProjectViewSet, basename='projects')
urlpatterns = [
path('api/', include(router.urls)),
path('api/auth/register/', register),
path('api/auth/login/', login),
]
How Do You Handle Database Migrations and Data Safety?
Handle database migrations safely by using Django's migration framework with custom migration scripts for data transformations, implementing database backups before migrations, and using a staging environment to test migrations before applying them to production.
Key practices for SaaS database management:
| Practice | Implementation | Impact |
|---|---|---|
| Zero-downtime migrations | Avoid dropping columns directly; use deprecation cycle | No user disruption |
| Data backups | Automated daily backups with pg_dump | Disaster recovery |
| Migration testing | Run migrations on staging database first | Catch errors early |
| Rollback plans | Keep reverse migrations working | Quick recovery |
| Seed data | Management commands for initial data | Consistent setup |
# apps/core/management/commands/seed_plans.py
from django.core.management.base import BaseCommand
from apps.billing.models import Plan
class Command(BaseCommand):
help = 'Seed subscription plans'
def handle(self, *args, **options):
plans = [
{
'name': 'Free',
'slug': 'free',
'price_monthly': 0,
'price_yearly': 0,
'max_users': 2,
'max_projects': 3,
'max_storage_gb': 1,
'has_api_access': False,
},
{
'name': 'Starter',
'slug': 'starter',
'price_monthly': 29,
'price_yearly': 290,
'max_users': 10,
'max_projects': 25,
'max_storage_gb': 10,
'has_api_access': True,
},
{
'name': 'Professional',
'slug': 'professional',
'price_monthly': 79,
'price_yearly': 790,
'max_users': 50,
'max_projects': 100,
'max_storage_gb': 50,
'has_api_access': True,
'has_priority_support': True,
},
]
for plan_data in plans:
Plan.objects.update_or_create(
slug=plan_data['slug'],
defaults=plan_data
)
self.stdout.write(f"Created/updated plan: {plan_data['name']}")
How Do You Deploy a Django SaaS Application to Production?
Deploy Django SaaS applications using Docker containers with Gunicorn as the WSGI server, PostgreSQL for the database, Redis for caching and Celery task queue, and Nginx as a reverse proxy, all orchestrated with Docker Compose or deployed to platforms like Railway.
# docker-compose.yml
version: '3.8'
services:
web:
build: .
command: gunicorn config.wsgi:application --bind 0.0.0.0:8000 --workers 3
volumes:
- .:/app
- static_volume:/app/staticfiles
env_file:
- .env
depends_on:
- db
- redis
db:
image: postgres:15
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
POSTGRES_DB: saas_db
POSTGRES_USER: saas_user
POSTGRES_PASSWORD: ${DB_PASSWORD}
redis:
image: redis:7-alpine
celery:
build: .
command: celery -A config worker -l info
env_file:
- .env
depends_on:
- db
- redis
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/conf.d/default.conf
- static_volume:/app/staticfiles
volumes:
postgres_data:
static_volume:
# config/settings/production.py
from .base import *
import os
DEBUG = False
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '').split(',')
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': os.getenv('DB_NAME'),
'USER': os.getenv('DB_USER'),
'PASSWORD': os.getenv('DB_PASSWORD'),
'HOST': os.getenv('DB_HOST'),
'PORT': os.getenv('DB_PORT', '5432'),
}
}
# Security
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 31536000
# Static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
# Cache
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': os.getenv('REDIS_URL', 'redis://redis:6379/0'),
}
}
# Celery
CELERY_BROKER_URL = os.getenv('REDIS_URL', 'redis://redis:6379/1')
What Reddit Communities Say About Django SaaS Development
Discussions across r/django, r/SaaS, and r/webdev highlight these insights:
-
"Django's admin panel is a huge advantage for SaaS." Many founders use Django admin as their internal dashboard, saving weeks of development time. You can customize it extensively before needing to build a custom admin interface.
-
"Start with the simplest multi-tenancy approach." The shared database with foreign key approach works for 90% of SaaS applications. Reddit users report that switching to schema-based isolation is rarely necessary unless you have strict compliance requirements.
-
"Django REST Framework is the best REST API library in any language." The serializer pattern, viewsets, and built-in browsable API make DRF incredibly productive for building APIs quickly.
-
"Do not build billing from scratch." Experienced SaaS developers consistently recommend using Stripe's library or similar services rather than implementing payment processing yourself. The complexity of handling failed payments, prorations, and tax calculations is enormous.
Practical Takeaway: Your Django SaaS Development Roadmap
Follow this roadmap to build your SaaS application:
- Week 1: Set up project structure, custom user model, and tenant models
- Week 2: Build authentication (registration, login, JWT tokens, password reset)
- Week 3: Implement core business logic with tenant isolation
- Week 4: Add subscription billing with Stripe (or eSewa/Khalti for Nepal)
- Week 5: Build REST API with proper permissions and documentation
- Week 6: Deploy with Docker, set up CI/CD, and launch
Django SaaS development is one of the highest-value skills for developers in Nepal. International companies frequently outsource SaaS backend development to experienced Django developers, with rates ranging from $30-80 per hour for skilled developers.
Frequently Asked Questions
Is Django good for building SaaS applications in 2026?
Yes, Django remains one of the top choices for SaaS backend development. Its mature ecosystem, built-in security features, ORM, and admin panel make it ideal for building SaaS products quickly. Companies like Instagram and Disqus prove that Django scales to millions of users.
How do I handle multi-tenancy in Django?
The simplest approach is using a shared database with a tenant foreign key on every model. Create a base TenantModel class and a custom manager that filters by tenant. For most applications, this provides sufficient isolation without the complexity of separate databases or schemas.
Should I use Django REST Framework or Django Ninja for my API?
Django REST Framework (DRF) is the safer choice with a larger ecosystem, more learning resources, and battle-tested reliability. Django Ninja is faster and uses Python type hints, but has a smaller community. For your first SaaS project, DRF is recommended.
How much does it cost to deploy a Django SaaS application?
You can start with free tiers on Railway or Render for development. For production with a PostgreSQL database, expect to pay $20-50 per month for a small application. As you scale, costs increase with database size, server capacity, and bandwidth. Managed services like AWS or DigitalOcean start around $50 per month for production workloads.
Can I build a SaaS product for the Nepali market with Django?
Absolutely. Django supports localization and internationalization out of the box. You can integrate Nepali payment gateways like eSewa and Khalti, support Nepali language content, and deploy on servers optimized for South Asian audiences. Several successful Nepali SaaS products are built on Django.
Learn Django SaaS Development at Swift Academy Pokhara
Want to build production-quality SaaS applications with Django? Swift Academy's Django course in Pokhara teaches you everything from project setup to deployment. You will build a complete SaaS application as your capstone project.
Our curriculum covers Django ORM, REST APIs, authentication, deployment with Docker, and real-world project architecture. Learn from experienced instructors who have built and shipped production Django applications.
Visit swiftacademy.com.np or visit our Pokhara campus to start your Django journey.
Related Articles
- Django vs Flask: Which Python Framework Should You Learn?
- How to Deploy Django Applications on AWS
- REST API Design Best Practices for Python Developers
Suggested Images
- Hero Image: Clean architecture diagram showing Django SaaS application components including database, API, authentication, and billing layers — Alt text: "Django SaaS application architecture diagram"
- Code Screenshot: Terminal showing Django project structure with apps directory and key files highlighted — Alt text: "Django SaaS project structure in terminal"
- Deployment Diagram: Docker containers running Django, PostgreSQL, Redis, and Nginx with connection arrows — Alt text: "Django SaaS deployment architecture with Docker"




