A comprehensive, production-ready multi-tenant e-commerce platform built with Django and Django REST Framework. This platform enables multiple independent online stores to operate on a single codebase with complete data isolation, advanced features, and AI-powered recommendations.
- Schema-based isolation - Complete data separation per tenant
- Subdomain routing - Automatic tenant detection
- Shared/tenant-specific apps - Flexible app configuration
- Custom domain support - Brand your stores
- Multiple product types - Simple, variable, grouped, digital
- Variant support - Colors, sizes, attributes
- Categories & brands - Hierarchical organization
- Product reviews - Customer ratings and reviews
- Advanced filtering - Search, sort, filter by multiple criteria
- SEO optimization - Meta tags, structured data
- Multi-warehouse support - Multiple storage locations
- Real-time tracking - Accurate stock levels
- Stock movements - Complete audit trail
- Low stock alerts - Automatic notifications
- Purchase orders - Supplier management
- Inventory reservations - Hold stock for pending orders
- Complete order lifecycle - Pending β Processing β Shipped β Delivered
- Order tracking - Real-time status updates
- Invoice generation - Automatic invoicing
- Shipping zones - Country-based shipping
- Shipping calculation - Dynamic cost calculation
- Order cancellation - With inventory release
- Multi-gateway support - Stripe, Paystack, PayPal
- Secure transactions - PCI compliance
- Payment tracking - Complete transaction history
- Refund processing - Full and partial refunds
- Webhook handling - Automatic status updates
- Payment retry - Failed payment recovery
- Multiple discount types - Percentage, fixed, BOGO, free shipping
- Coupon management - Single-use and bulk generation
- Customer targeting - Group-specific promotions
- Usage limits - Total and per-customer limits
- Promotion analytics - Performance tracking
- Collaborative filtering - Users who bought X also bought Y
- Content-based filtering - Similar product recommendations
- Trending products - Popular items algorithm
- Personalized recommendations - Hybrid ML approach
- Frequently bought together - Market basket analysis
- Behavior tracking - Comprehensive analytics
- Customer accounts - Registration and profiles
- Address management - Multiple addresses
- Customer groups - Segmentation and targeting
- Order history - Complete purchase records
- Wishlist - Save for later
- Loyalty points - Reward system
- Session-based carts - Anonymous shopping
- User-based carts - Persistent carts
- Cart merging - Combine anonymous and user carts
- Inventory validation - Real-time stock checks
- Cart abandonment tracking - Recovery campaigns
- JWT authentication - Secure token-based auth
- Two-factor authentication - Enhanced security
- Email verification - Account confirmation
- Password reset - Secure recovery flow
- Account lockout - Brute force protection
- Rate limiting - DDoS prevention
- Audit logging - Complete security trail
- RESTful API - Clean, consistent endpoints
- Swagger/OpenAPI - Interactive documentation
- API versioning - Backward compatibility
- Comprehensive filtering - Django filters
- Pagination - Efficient data handling
- CORS support - Cross-origin requests
- Django 5.0+ - Python web framework
- Django REST Framework - API development
- django-tenants - Multi-tenancy support
- PostgreSQL - Primary database
- Redis - Caching and sessions
- Celery - Background task processing
- djangorestframework-simplejwt - JWT authentication
- django-cors-headers - CORS support
- python-decouple - Environment management
- drf-spectacular - OpenAPI/Swagger documentation
- django-filter - Advanced filtering
- stripe - Stripe integration
- paystack - Paystack integration
- paypal - PayPal integration (SDK)
django-multi-tenants/
βββ api/ # Core API configuration
β βββ authentication.py # Custom auth backends
β βββ permissions.py # Custom permissions (15+ classes)
β βββ throttles.py # Rate limiting
β βββ urls.py # Main API routing
β βββ views.py # Authentication views
βββ tenants/ # Multi-tenancy app
β βββ models.py # Tenant and Domain models
βββ products/ # Product management
β βββ models.py # Product, Category, Brand, Review
β βββ serializers.py # Product serializers
β βββ views.py # Product CRUD + Reviews
β βββ filters.py # Product filtering
β βββ urls.py # Product endpoints
βββ inventory/ # Inventory management
β βββ models.py # Warehouse, Stock, PO
β βββ serializers.py # Inventory serializers
β βββ views.py # Inventory CRUD
β βββ filters.py # Inventory filtering
β βββ urls.py # Inventory endpoints
βββ orders/ # Order management
β βββ models.py # Order, OrderItem, Shipping
β βββ serializers.py # Order serializers
β βββ views.py # Order CRUD + tracking
β βββ filters.py # Order filtering
β βββ urls.py # Order endpoints
βββ payments/ # Payment processing
β βββ models.py # Payment, Refund
β βββ serializers.py # Payment serializers
β βββ views.py # Payment processing
β βββ filters.py # Payment filtering
β βββ gateways/ # Payment gateway implementations
β β βββ stripe_gateway.py
β β βββ paystack_gateway.py
β β βββ paypal_gateway.py
β βββ urls.py # Payment endpoints
βββ promotions/ # Promotions & coupons
β βββ models.py # Promotion, Coupon
β βββ serializers.py # Promotion serializers
β βββ views.py # Promotion CRUD + validation
β βββ filters.py # Promotion filtering
β βββ urls.py # Promotion endpoints
βββ recommendations/ # AI recommendation engine
β βββ models.py # Interaction, RecommendationLog
β βββ serializers.py # Recommendation serializers
β βββ views.py # Recommendation algorithms
β βββ urls.py # Recommendation endpoints
βββ customers/ # Customer management
β βββ models.py # Customer, Address, Group
β βββ serializers.py # Customer serializers
β βββ views.py # Customer CRUD
β βββ filters.py # Customer filtering
β βββ urls.py # Customer endpoints
βββ cart/ # Shopping cart
β βββ models.py # Cart, CartItem, Wishlist
β βββ serializers.py # Cart serializers
β βββ views.py # Cart management
β βββ urls.py # Cart endpoints
βββ config/ # Django settings
β βββ settings.py # Main settings
β βββ urls.py # Root URL configuration
β βββ wsgi.py # WSGI configuration
βββ docs/ # Documentation
β βββ project-description.md # Project specification
βββ requirements.txt # Python dependencies
βββ manage.py # Django management script
βββ README.md # This file
- Python 3.10 or higher
- PostgreSQL 13 or higher
- Redis 6 or higher
- Git
git clone https://github.com/yourusername/django-multi-tenants.git
cd django-multi-tenantspython -m venv venv
# Windows
venv\Scripts\activate
# Linux/Mac
source venv/bin/activatepip install -r requirements.txtCreate a .env file in the project root (optional - all settings have defaults):
Note: The application uses
os.getenv()for environment variables. You can either:
- Create a
.envfile and load it usingpython-dotenv- Set environment variables directly in your system
- Use the default values (suitable for development)
# Django
DEBUG=True
SECRET_KEY=your-secret-key-here
ALLOWED_HOSTS=localhost,127.0.0.1
# Database
DATABASE_NAME=ecommerce_db
DATABASE_USER=postgres
DATABASE_PASSWORD=your-password
DATABASE_HOST=localhost
DATABASE_PORT=5432
# Redis
REDIS_URL=redis://localhost:6379/0
# JWT
JWT_SECRET_KEY=your-jwt-secret-key
# Email
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_HOST_USER=your-email@gmail.com
EMAIL_HOST_PASSWORD=your-email-password
EMAIL_USE_TLS=True
# Payment Gateways
STRIPE_SECRET_KEY=sk_test_...
STRIPE_PUBLISHABLE_KEY=pk_test_...
STRIPE_WEBHOOK_SECRET=whsec_...
PAYSTACK_SECRET_KEY=sk_test_...
PAYSTACK_PUBLIC_KEY=pk_test_...
PAYSTACK_WEBHOOK_SECRET=...
PAYPAL_CLIENT_ID=...
PAYPAL_CLIENT_SECRET=...
PAYPAL_MODE=sandbox
# Frontend URL (for CORS)
FRONTEND_URL=http://localhost:3000
# Celery
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0# Create PostgreSQL database
psql -U postgres
CREATE DATABASE ecommerce_db;
\q
# Run migrations for shared apps
python manage.py migrate_schemas --shared
# Run migrations for tenant apps
python manage.py migrate_schemasNote: You'll need to create tenants using Django shell or create a custom management command. See the Multi-Tenancy Setup section below for details.
python manage.py createsuperuser# Terminal 1: Django server
python manage.py runserver
# Terminal 2: Celery worker (optional)
celery -A config worker -l info
# Terminal 3: Celery beat (optional)
celery -A config beat -l info
# Terminal 4: Flower - Celery monitoring (optional)
celery -A config flowerAccess the application:
- Main Application: http://localhost:8000
- Admin Panel: http://localhost:8000/admin/
- API Documentation: http://localhost:8000/api/docs/
- Flower Monitoring: http://localhost:5555 (if running)
- Multi-tenant architecture with schema-based isolation
- Complete product management (CRUD, categories, brands, reviews)
- Inventory management (warehouses, stock movements, alerts, purchase orders)
- Order management (full lifecycle, tracking, invoicing)
- Payment processing (Stripe, Paystack, PayPal integration)
- Promotions & coupon system (multiple discount types)
- AI-powered recommendations (5 algorithms)
- Customer management (accounts, addresses, groups)
- Shopping cart & wishlist
- Comprehensive authentication & security (JWT, 2FA, rate limiting)
- API documentation (Swagger/OpenAPI)
- Celery background task infrastructure
- Redis caching for recommendations
- Email notification tasks (abandoned cart, order updates)
- Email template system
- Tenant creation management command
- Docker containerization
- Advanced analytics dashboard
- GraphQL API support
- Multi-language support (i18n)
- Advanced reporting & exports
- Marketplace features
- Mobile app integration
- Real-time notifications (WebSockets)
Once the server is running, access the interactive API documentation:
- Swagger UI: http://localhost:8000/api/docs/
- ReDoc: http://localhost:8000/api/redoc/
- OpenAPI Schema: http://localhost:8000/api/schema/
POST /register/- User registrationPOST /login/- User login (JWT)POST /logout/- User logoutPOST /refresh/- Refresh JWT tokenPOST /verify-email/- Email verificationPOST /forgot-password/- Password reset requestPOST /reset-password/- Password resetPOST /2fa/enable/- Enable 2FAPOST /2fa/verify/- Verify 2FA code
GET /products/- List productsPOST /products/- Create product (admin)GET /products/{id}/- Get product detailsPUT /products/{id}/- Update product (admin)DELETE /products/{id}/- Delete product (admin)GET /categories/- List categoriesGET /brands/- List brandsGET /reviews/- List reviewsPOST /products/{id}/reviews/- Add review
GET /warehouses/- List warehousesGET /inventory-items/- List inventoryPOST /stock-movements/- Record stock movementGET /stock-alerts/- Get low stock alertsGET /purchase-orders/- List purchase ordersPOST /purchase-orders/- Create PO (admin)
GET /orders/- List ordersPOST /orders/- Create orderGET /orders/{id}/- Get order detailsPOST /orders/{id}/cancel/- Cancel orderGET /orders/{id}/track/- Track orderGET /orders/{id}/invoice/- Get invoicePOST /orders/{id}/reorder/- ReorderGET /shipping-zones/- List shipping zonesPOST /shipping-zones/calculate/- Calculate shipping
GET /payments/- List paymentsPOST /payments/create_intent/- Create payment intentPOST /payments/confirm/- Confirm paymentPOST /payments/{id}/verify/- Verify paymentGET /refunds/- List refundsPOST /refunds/- Create refund (admin)POST /webhooks/{gateway}/- Payment webhooks
GET /promotions/- List promotionsGET /promotions/active/- Get active promotionsGET /promotions/featured/- Get featured promotionsPOST /coupons/validate/- Validate couponPOST /coupons/apply/- Apply coupon to orderPOST /coupons/bulk_generate/- Bulk generate coupons (admin)
POST /track/- Track interactionPOST /get-recommendations/- Get recommendationsPOST /similar-products/- Get similar productsPOST /trending/- Get trending productsPOST /personalized/- Get personalized recommendationsPOST /frequently-bought-together/- Get bundle suggestionsPOST /recently-viewed/- Get recently viewed
GET /customers/- List customers (admin)GET /customers/me/- Get current user profilePUT /customers/me/- Update profileGET /addresses/- List addressesPOST /addresses/- Add addressGET /groups/- List customer groups
GET /cart/- Get cartPOST /cart/add/- Add to cartPUT /cart/update/- Update cart itemDELETE /cart/remove/{id}/- Remove from cartPOST /cart/clear/- Clear cartGET /wishlist/- Get wishlistPOST /wishlist/add/- Add to wishlist
from tenants.models import Tenant, Domain
# Create tenant
tenant = Tenant.objects.create(
schema_name='tenant1',
name='Tenant 1',
business_name='Tenant 1 Store',
business_email='admin@tenant1.com',
business_phone='+1234567890',
currency='USD',
timezone='UTC'
)
# Create domain
domain = Domain.objects.create(
domain='tenant1.localhost',
tenant=tenant,
is_primary=True
)Add to your /etc/hosts (Linux/Mac) or C:\Windows\System32\drivers\etc\hosts (Windows):
127.0.0.1 tenant1.localhost
127.0.0.1 tenant2.localhost
Access tenants:
- Tenant 1: http://tenant1.localhost:8000
- Tenant 2: http://tenant2.localhost:8000
# 1. Add items to cart
POST /api/v1/cart/add/
{
"product_id": 1,
"quantity": 2,
"variant_id": 3
}
# 2. Validate coupon (optional)
POST /api/v1/promotions/coupons/validate/
{
"code": "SAVE20",
"cart_total": 100.00
}
# 3. Calculate shipping
POST /api/v1/orders/shipping-zones/calculate/
{
"country": "US",
"subtotal": 100.00
}
# 4. Create order
POST /api/v1/orders/orders/
{
"shipping_amount": 10.00,
"tax_amount": 8.00,
"payment_method": "card",
"billing_address": {...},
"shipping_address": {...},
"coupon_code": "SAVE20"
}
# 5. Create payment intent
POST /api/v1/payments/payments/create_intent/
{
"order_id": 123,
"payment_method": "card",
"gateway": "stripe"
}
# 6. Confirm payment (after user completes payment)
POST /api/v1/payments/payments/confirm/
{
"payment_intent_id": "pi_abc123",
"gateway": "stripe"
}
# 7. Track order
GET /api/v1/orders/orders/123/track/# Track user interaction
POST /api/v1/recommendations/track/
{
"product_id": 123,
"interaction_type": "view",
"source": "homepage"
}
# Get personalized recommendations
POST /api/v1/recommendations/personalized/
{
"limit": 10,
"page_type": "homepage"
}
# Get similar products
POST /api/v1/recommendations/similar-products/
{
"product_id": 123,
"limit": 5
}
# Get trending products
POST /api/v1/recommendations/trending/
{
"days": 7,
"limit": 20
}-
Authentication Security
- JWT token authentication
- Token refresh mechanism
- Two-factor authentication (2FA)
- Email verification
- Account lockout after failed attempts
- Password strength validation
-
API Security
- Rate limiting (15+ throttle classes)
- CORS configuration
- CSRF protection
- Input validation
- SQL injection prevention
- XSS protection
-
Payment Security
- PCI compliance (no raw card storage)
- Webhook signature verification
- Transaction audit trail
- Secure payment gateway integration
-
Data Security
- Tenant data isolation (schema-based)
- Encrypted sensitive data
- Secure password hashing
- Audit logging
- GDPR compliance ready
-
Infrastructure Security
- HTTPS enforcement (production)
- HSTS headers
- Secure cookies
- Environment variable configuration
- Redis caching for recommendations (30 min - 1 hour TTL)
- Query optimization - select_related, prefetch_related
- Database indexing - Composite indexes on frequently queried fields
- API pagination - Efficient data handling
The platform uses Celery with Redis for asynchronous task processing:
Configured Task Queues:
recommendations- ML-based recommendation updatesorders- Order processing and notificationscart- Cart cleanup and abandoned cart recoveryinventory- Stock level updates and alertspromotions- Promotion analytics and expirationcustomers- Customer data processing
Implemented Tasks:
- Recommendation precomputation (every 1 hour)
- Product similarity calculations
- Trending products analysis
- Personalized recommendations
Scheduled Tasks (Celery Beat):
update_product_recommendations- Runs hourly to refresh cached recommendationsclear_recommendation_cache- Manual cache clearing task
# Run all tests
python manage.py test
# Run specific app tests
python manage.py test products
python manage.py test orders
# Run with coverage
coverage run --source='.' manage.py test
coverage report-
Product Analytics
- View counts
- Sales performance
- Rating statistics
- Popular products
-
Order Analytics
- Order summary
- Revenue tracking
- Order status distribution
-
Customer Analytics
- Behavior analysis
- Category preferences
- Brand preferences
- Conversion rates
-
Recommendation Analytics
- Click-through rates
- Conversion rates
- Algorithm performance
- A/B testing results
-
Promotion Analytics
- Usage statistics
- Discount given
- Most used promotions
- Set
DEBUG=False - Configure
ALLOWED_HOSTS - Set up PostgreSQL production database
- Configure Redis for production
- Set up static file serving (S3/CDN)
- Configure email service (SendGrid/AWS SES)
- Set up SSL/HTTPS
- Configure payment gateway production keys
- Set up monitoring (Sentry, New Relic)
- Configure backup strategy
- Set up logging
- Configure Celery workers
- Set up load balancer (if needed)
Note: Docker configuration is currently in development. A complete
docker-compose.ymlwith all services will be available soon.
Planned Docker Setup:
- PostgreSQL container for database
- Redis container for caching and Celery broker
- Django web application container
- Celery worker containers (multiple queues)
- Celery beat scheduler container
- Flower monitoring container
- Nginx reverse proxy (production)
# If you encounter migration conflicts, reset migrations for tenant schemas
python manage.py migrate_schemas --shared
python manage.py migrate_schemas# Make sure Redis is running
redis-server
# Test connection
redis-cli ping
# Should return: PONG# Check Celery worker is running
celery -A config worker -l info
# Check if Redis broker is accessible
celery -A config inspect active# Ensure all payment gateway packages are installed
pip install stripe pypaystack2 paypalrestsdkThis usually means you haven't created a tenant yet. Create one using Django shell:
python manage.py shell
>>> from tenants.models import Tenant, Domain
>>> tenant = Tenant.objects.create(schema_name='public', name='Public')
>>> Domain.objects.create(domain='localhost', tenant=tenant, is_primary=True)python manage.py collectstatic --noinput- Check the
/docsdirectory for detailed documentation - Review API documentation at
/api/docs/ - Open an issue on GitHub with detailed error logs
- Include your Python version, Django version, and OS
Contributions are welcome! Please follow these guidelines:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
- Follow PEP 8 style guide
- Write comprehensive docstrings
- Add unit tests for new features
- Update documentation as needed
This project is licensed under the MIT License - see the LICENSE file for details.
- Your Name - Initial work - YourGitHub
- Django and Django REST Framework communities
- django-tenants for multi-tenancy support
- All open-source contributors
For support, email support@yourdomain.com or open an issue on GitHub.
- Email notification system (abandoned cart, order updates)
- Email template infrastructure
- Tenant management command
- Docker containerization
- Unit tests for all apps
- Advanced analytics dashboard
- GraphQL API support
- Multi-language support (i18n)
- Advanced reporting & exports
- Real-time notifications (WebSockets)
- Mobile app (React Native)
- Marketplace features
- Dropshipping integration
- Advanced SEO tools
- Multi-currency enhancement
- AI chatbot integration
- Total Apps: 10+
- API Endpoints: 100+
- Models: 30+
- Custom Permissions: 15+
- Recommendation Algorithms: 5
- Payment Gateways: 3
- Lines of Code: 15,000+
This platform is perfect for:
- SaaS E-Commerce - Multi-tenant marketplace platform
- B2B Wholesale - Supplier and distributor networks
- Multi-Brand Retail - Multiple stores under one roof
- Franchise Management - Centralized franchise system
- White-Label Solutions - Customizable for resellers
- Educational Stores - School/university bookstores
- Nonprofit Organizations - Multiple chapter stores
Built with β€οΈ using Django and DRF
For detailed documentation, visit the /docs directory or check out the interactive API documentation at /api/docs/.