Django comprehensive practical project - complete guide to e-commerce platform development | Daoman PythonAI

#django comprehensive practical project - a complete guide to e-commerce platform development

📂 Phase: Part 4 - Practical Project 🎯 Difficulty Level: Expert ⏰ Estimated study time: 12-15 hours 🎒 Prerequisite Knowledge: Complete all chapters of the first three parts

Project Overview

This tutorial will take you from scratch to build a fully functional enterprise-level e-commerce platform. The project adopts a microservice architecture and covers core business modules such as user management, product management, order processing, and payment integration. Through this practical project, you will comprehensively use various advanced-features of Django and master modern engineering practices such as microservices and containerized deployment.

Core business functions

  • User registration/login/identity authentication
  • Product browsing/search/category display
  • Shopping cart management (add, delete, modify and check)
  • Full life cycle processing of orders (Creation → Payment → Shipping → Completion)
  • Integration of multiple payment methods (Stripe, Alipay, WeChat, etc.)
  • Logistics status tracking and notification

Technical architecture goals

  • Microservice architecture: each business module is independently developed, deployed, and expanded
  • High availability: service redundancy, circuit breaker degradation, load balancing
  • Scalability: supports horizontal expansion to adapt to business growth
  • Security: multi-layer authentication, data encryption, and anti-attack measures
  • Performance optimization: caching, asynchronous tasks, database index optimization

Technology stack selection

The technology selection of this project takes into account development efficiency and long-term maintenance, and fully considers the activity and ecological integrity of the open source community.

Backend Technology Stack:

  • django 4.2+ - a full-featured web framework that provides out-of-the-box capabilities such as ORM, authentication, and management backend
  • django REST Framework - a powerful tool for building RESTful APIs
  • PostgreSQL - main database, stable performance, supports JSON fields and full-text search
  • Redis - cache hotspot data, store sessions, and implement distributed locks
  • Celery - Asynchronous task processing, such as sending emails and generating reports
  • RabbitMQ / Kafka - message queue, used for decoupling and peak cutting between services

Front-end technology stack:

  • Vue.js/React - modern front-end framework for building single-page applications
  • Axios - HTTP client, interacts with backend API
  • Element UI / Ant Design - enterprise-level UI component library to quickly build a backend management interface
  • Webpack - module packaging tool

Infrastructure:

  • Docker - Containerized operation to ensure environmental consistency
  • Nginx——Reverse proxy and static resource service
  • Gunicorn - WSGI application server
  • Kubernetes —— Production environment container orchestration to achieve automatic scaling and zero-downtime deployment

Project architecture design

Panorama of microservice architecture

We split the entire e-commerce system into multiple microservices. Each service has an independent database and exposes interfaces to the outside world through the API gateway. Asynchronous communication between services occurs via REST or message queue.

┌─────────────────────┐      ┌─────────────────────┐      ┌─────────────────────┐
│    API Gateway      │────▶ │    Gateway Route    │────▶ │      Frontend       │
└─────────────────────┘      └─────────────────────┘      └─────────────────────┘


┌─────────────────────┐      ┌─────────────────────┐      ┌─────────────────────┐
│    Auth Service     │      │    User Service     │      │   Product Service   │
└─────────────────────┘      └─────────────────────┘      └─────────────────────┘
          │                            │                            │
          ▼                            ▼                            ▼
┌─────────────────────┐      ┌─────────────────────┐      ┌─────────────────────┐
│    Cart Service     │      │    Order Service    │      │   Payment Service   │
└─────────────────────┘      └─────────────────────┘      └─────────────────────┘

This architecture brings the following core advantages:

  1. Independent deployment and iteration: Each service can be released independently without affecting each other.
  2. Data Isolation: The service has an independent database to avoid single points of failure.
  3. Asynchronous decoupling: Asynchronousize time-consuming operations through message queues to improve overall throughput
  4. High Availability and Elastic Scaling: Stateless services can be easily expanded horizontally and combined with load balancing to achieve high availability
  5. Technical Diversity: Different services can choose the most appropriate language or storage solution according to their needs (this article uses django uniformly)

Project directory structure

ecommerce-platform/
├── docker-compose.yml          # 本地开发环境编排
├── services/                   # 微服务目录
   ├── gateway/                # API 网关
   ├── user/                   # 用户服务
   ├── product/                # 商品服务
   ├── order/                  # 订单与购物车服务
   ├── payment/                # 支付服务
   ├── cart/                   # 购物车独立服务(可选项)
   ├── search/                 # 搜索服务
   └── notification/           # 通知服务
├── frontend/                   # 前端项目
├── shared/                     # 共享工具库、中间件
├── docs/                       # 项目文档
├── scripts/                    # 运维脚本
├── tests/                      # 集成测试用例
└── README.md

Core service implementation

Next, we will delve into the core implementation of each microservice one by one. Each service will demonstrate key model design, view logic, and best practices.

1. User service module

User service is the foundation of the entire platform and is responsible for registration, login, personal information management, etc.

User model design

We inherit django’sAbstractUser, and expand fields such as mobile phone number, email verification, avatar, etc., and use UUID as the primary key to improve security.

# services/user/user_service/apps/user_auth/models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
import uuid

class User(AbstractUser):
    """扩展的用户模型"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    phone = models.CharField(max_length=20, blank=True, unique=True)
    avatar = models.URLField(blank=True)
    email_verified = models.BooleanField(default=False)
    phone_verified = models.BooleanField(default=False)
    is_premium = models.BooleanField(default=False, verbose_name="是否高级会员")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'users'

User registration interface

The registration interface will simultaneously create users, profiles and security settings, and send verification emails. passRefreshTokenDirectly returns the JWT token, reducing login steps.

# services/user/user_service/apps/user_auth/views.py
from rest_framework.views import APIView
from rest_framework.permissions import AllowAny
from rest_framework_simplejwt.tokens import RefreshToken
from .serializers import UserRegistrationSerializer
from .utils import send_verification_email

class UserRegistrationView(APIView):
    """用户注册"""
    permission_classes = [AllowAny]

    def post(self, request):
        serializer = UserRegistrationSerializer(data=request.data)
        if not serializer.is_valid():
            return ErrorResponse(serializer.errors, status=400)

        try:
            user = serializer.save()
            # 发送验证邮件(异步调用 Celery 任务更佳,此处为演示省略)
            send_verification_email(user.email, user.id)

            # 生成 JWT 令牌
            refresh = RefreshToken.for_user(user)

            return SuccessResponse({
                'user': {
                    'id': str(user.id),
                    'username': user.username,
                    'email': user.email,
                    'phone': user.phone,
                },
                'tokens': {
                    'refresh': str(refresh),
                    'access': str(refresh.access_token),
                },
                'message': '注册成功,请检查邮箱完成验证'
            }, status=201)
        except Exception as e:
            logger.error(f"用户注册失败: {str(e)}")
            return ErrorResponse({'detail': '注册失败,请稍后重试'}, status=500)

2. Product service module

Product service is responsible for maintaining product data, classification, brand, inventory and other information.

Product model example

The product model includes status transfer, ratings, sales statistics, etc., and associates categories and brands through foreign keys.

# services/product/product_service/models.py
class Product(models.Model):
    """商品"""
    PRODUCT_STATUS_CHOICES = [
        ('draft', '草稿'),
        ('pending_review', '待审核'),
        ('approved', '已审核'),
        ('active', '已上架'),
        ('inactive', '已下架'),
        ('discontinued', '停止销售'),
    ]

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200, verbose_name="商品名称")
    slug = models.SlugField(unique=True, max_length=250)
    description = models.TextField(verbose_name="商品描述")
    category = models.ForeignKey(Category, on_delete=models.SET_NULL,
                                 null=True, related_name='products')
    brand = models.ForeignKey(Brand, on_delete=models.SET_NULL,
                              null=True, related_name='products')
    sku = models.CharField(max_length=100, unique=True, verbose_name="SKU")
    price = models.DecimalField(max_digits=10, decimal_places=2,
                                validators=[MinValueValidator(0)])
    status = models.CharField(max_length=20, choices=PRODUCT_STATUS_CHOICES,
                              default='draft', verbose_name="商品状态")
    rating = models.DecimalField(max_digits=3, decimal_places=2,
                                 default=0, validators=[MinValueValidator(0),
                                                        MaxValueValidator(5.0)])
    review_count = models.PositiveIntegerField(default=0)
    view_count = models.PositiveIntegerField(default=0)
    sales_count = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'products'

3. Order and shopping cart services

The order service contains the logic of the shopping cart, and the shopping cart data is usually stored in Redis or a database (in this case, it is stored in the database) for easy persistence.

Shopping cart view

# services/order/order_service/views.py
class ShoppingCartView(APIView):
    """购物车管理"""
    permission_classes = [IsAuthenticated]

    def get(self, request):
        """获取当前用户的购物车"""
        cart, _ = ShoppingCart.objects.get_or_create(
            user_id=request.user.id,
            defaults={'items': [], 'total_items': 0, 'total_amount': 0.00}
        )
        self.update_cart_totals(cart)
        serializer = ShoppingCartSerializer(cart)
        return SuccessResponse(serializer.data)

    def post(self, request):
        """添加商品到购物车"""
        product_id = request.data.get('product_id')
        quantity = int(request.data.get('quantity', 1))

        if not product_id:
            return ErrorResponse({'error': '商品ID不能为空'}, status=400)

        # 检查商品是否存在且库存充足
        product = self.check_product_availability(product_id, quantity)
        if not product:
            return ErrorResponse({'error': '商品不存在或库存不足'}, status=400)

        cart, _ = ShoppingCart.objects.get_or_create(
            user_id=request.user.id,
            defaults={'items': [], 'total_items': 0, 'total_amount': 0.00}
        )

        # 更新购物车商品项
        cart.items.append({
            'product_id': str(product_id),
            'quantity': quantity,
            'unit_price': float(product.price),
            'total_price': float(product.price * quantity),
            'added_at': timezone.now().isoformat()
        })
        cart.save()
        self.update_cart_totals(cart)

        serializer = ShoppingCartSerializer(cart)
        return SuccessResponse({
            'cart': serializer.data,
            'message': '已加入购物车'
        })

4. Payment service module

The payment service encapsulates different payment gateways through strategic models to facilitate the expansion of Alipay, WeChat and other channels.

Payment gateway base class

# services/payment/payment_service/gateways/base.py
from abc import ABC, abstractmethod
from decimal import Decimal
from typing import Dict, Any

class BasePaymentGateway(ABC):
    """支付网关抽象基类"""

    def __init__(self, config: Dict[str, Any]):
        self.config = config

    @abstractmethod
    def create_payment(self, amount: Decimal, currency: str,
                       order_info: Dict[str, Any]) -> Dict[str, Any]:
        """发起支付请求"""
        pass

    @abstractmethod
    def verify_payment(self, transaction_id: str) -> Dict[str, Any]:
        """验证支付结果"""
        pass

    @abstractmethod
    def refund_payment(self, transaction_id: str,
                       amount: Decimal = None) -> Dict[str, Any]:
        """执行退款"""
        pass

In actual projects, you will implement them separatelyStripeGatewayAlipayGatewayand other subclasses, dynamically selected through configuration.

API gateway implementation

The API gateway is the unified entrance to the entire system and is responsible for request routing, authentication and authorization, flow control and circuit breaker protection.

# services/gateway/gateway_app/views.py
class GatewayView(View):
    """API 网关主视图"""

    def __init__(self):
        super().__init__()
        self.service_discovery = ServiceDiscovery()  # 服务发现
        self.load_balancer = LoadBalancer()          # 负载均衡
        self.api_client = APIClient()                # HTTP 客户端
        self.circuit_breaker = CircuitBreaker()      # 熔断器

    def dispatch(self, request, *args, **kwargs):
        """请求分发"""
        path = request.path
        method = request.method

        # 1. 根据路由表找到对应的微服务
        try:
            route = APIRoute.objects.get(
                path=path,
                methods__contains=[method],
                is_active=True
            )
        except APIRoute.DoesNotExist:
            return JsonResponse({'error': '路由未找到'}, status=404)

        # 2. 从服务发现获取一个可用实例
        instance = self.service_discovery.get_instance(route.target_service.name)
        if not instance:
            return JsonResponse({'error': '服务暂不可用'}, status=503)

        # 3. 转发请求,并启用熔断保护
        headers = self._build_headers(request)
        body = request.body.decode('utf-8') if request.body else None
        query_params = dict(request.GET)

        try:
            response_data = self.circuit_breaker.call(
                route.target_service.name,
                self.api_client.forward_request,
                instance, path, method, headers, body, query_params
            )
            # 记录访问日志
            self._log_request(route, request, response_data)

            # 4. 构造响应返回客户端
            response = HttpResponse(
                content=response_data['body'],
                status=response_data['status_code'],
                content_type='application/json'
            )
            for key, value in response_data['headers'].items():
                response[key] = value
            return response

        except Exception as e:
            logger.error(f"网关转发异常: {e}")
            return JsonResponse({'error': '内部服务器错误'}, status=500)

The gateway layer can also embed security policies such as JWT verification, IP black and white lists, and Rate Limiting to effectively protect back-end services.

Deployment and online

Quick start using Docker Compose

Local development and test environments can be accessed viadocker-compose.ymlBuild all dependent services with one click.

version: '3.8'

services:
  postgres:
    image: postgres:15
    container_name: ecommerce_postgres
    environment:
      POSTGRES_DB: ecommerce
      POSTGRES_USER: ecommerce_user
      POSTGRES_PASSWORD: ${DB_PASSWORD:-password}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"
    networks:
      - ecommerce_network

  redis:
    image: redis:7-alpine
    container_name: ecommerce_redis
    ports:
      - "6379:6379"
    volumes:
      - redis_data:/data
    networks:
      - ecommerce_network

  gateway:
    build: ./services/gateway
    container_name: ecommerce_gateway
    depends_on:
      - postgres
      - redis
    environment:
      - DEBUG=${DEBUG:-False}
      - DB_HOST=postgres
      - REDIS_URL=redis://redis:6379/0
    ports:
      - "8000:8000"
    networks:
      - ecommerce_network
    restart: unless-stopped

  user-service:
    build: ./services/user
    container_name: ecommerce_user_service
    depends_on:
      - postgres
      - redis
    ports:
      - "8001:8001"
    networks:
      - ecommerce_network
    restart: unless-stopped

volumes:
  postgres_data:
  redis_data:

networks:
  ecommerce_network:
    driver: bridge

Just executedocker-compose up -dThe entire development environment can be started.

Production environment: Kubernetes deployment

For highly available production environments, we use Kubernetes for container orchestration. The following is a typical Deployment configuration for deploying the Gateway service and configuring health checks and resource limits.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: gateway
  namespace: ecommerce-platform
  labels:
    app: gateway
spec:
  replicas: 3                                    # 多个副本保证高可用
  selector:
    matchLabels:
      app: gateway
  template:
    metadata:
      labels:
        app: gateway
    spec:
      containers:
      - name: gateway
        image: ecommerce/gateway:latest
        ports:
        - containerPort: 8000
        env:
        - name: DB_HOST
          value: postgres-service
        - name: REDIS_URL
          value: redis://redis-service:6379/0
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
        livenessProbe:                           # 存活探针
          httpGet:
            path: /health/
            port: 8000
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:                          # 就绪探针
          httpGet:
            path: /health/
            port: 8000
          initialDelaySeconds: 5
          periodSeconds: 5

The scaling of a single service only needs to be adjustedreplicasNumber; combined with Service and Ingress, external traffic can be smoothly distributed to each Pod.

Project summary

Through this tutorial, we built a production-level e-commerce platform from scratch. Not only did you learn how to build a RESTful API with django, you also gained an in-depth understanding of:

  • How to split into independent microservices according to business boundaries
  • How to design core modules such as user authentication, product management, ordering, and payment
  • How to achieve unified entrance and traffic management through API gateway
  • How to use Docker and Kubernetes to achieve one-click deployment and elastic scaling
  • How to combine Redis, Celery, and message queue to optimize performance and decouple services

This project is not only a comprehensive exercise of the Django technology stack, but also a practical bridge to enterprise-level microservice architecture. I hope you can further expand the functions on this basis, such as adding recommendation system, intelligent search, data dashboard, etc., to create your own full-stack e-commerce application!

Tip: You can find the complete project source code at GitHub 仓库, which will be better if used with this article.