基于Django的购物系统
文章目录
- 基于Django的购物系统
- 一、引言
- 二、前端分析
- 2.1 整体架构
- 2.2 页面布局与样式
- 2.3 交互功能
- 三、后端分析
- 3.1 框架选择
- 3.2 功能模块
- 3.3 中间件
- 四、数据库分析
- 4.1 数据库选择
- 4.2 数据表结构
- 4.3 数据插入
- 五、总结
- 源码下载
基于Django的购物系统
博主介绍:✌安替-AnTi:CSDN博客专家、掘金/华为云//InfoQ等平台优质作者,硕士研究生毕业。专注于算法开发、爬虫逆向和毕业项目实战✌
🍅文末有源码链接🍅
👇🏻 精彩专栏推荐订阅👇🏻 不然下次找不到哟
感兴趣的同学可以先行收藏,还有大家在毕设选题,项目以及文档编写等相关问题都可以给我留言咨询,希望帮助更多的人,也承接各种算法类、开发类毕业设计论文&程序编写。
一、引言
本购物系统是一个基于 Django 框架开发的电商平台,旨在为用户提供便捷的购物体验。本报告将从前端、后端、数据库三个角度对该系统的源码进行详细分析。
二、前端分析
2.1 整体架构
前端部分主要负责用户界面的展示和交互,使用了 HTML、CSS 和 JavaScript 等技术。通过 Django 的模板引擎,将动态数据与静态页面相结合,实现了页面的动态渲染。
2.2 页面布局与样式
- 基础模板:templates/base.html 是整个系统的基础模板,定义了页面的整体结构,包括导航栏、主体内容区域和页脚。页脚部分提供了关于我们、联系方式和快速链接等信息,方便用户了解平台和进行操作。
<!-- 页脚 -->
<footer class="footer mt-auto"><div class="container"><div class="row"><div class="col-md-4"><h5>关于我们</h5><p>我们是一家专注于提供优质商品的电商平台,致力于为客户提供最好的购物体验。</p></div><div class="col-md-4"><h5>联系方式</h5><ul class="list-unstyled"><li><i class="bi bi-envelope"></i> 邮箱:contact@shoppingsystem.com</li><li><i class="bi bi-telephone"></i> 电话:400-123-4567</li><li><i class="bi bi-geo-alt"></i> 地址:中国上海市浦东新区张江高科技园区</li></ul></div><div class="col-md-4"><h5>快速链接</h5><ul class="list-unstyled"><li><a href="{% url 'home' %}">首页</a></li><li><a href="{% url 'product_list' %}">全部商品</a></li>{% if user.is_authenticated %}<li><a href="{% url 'profile' %}">个人资料</a></li><li><a href="{% url 'order_history' %}">我的订单</a></li>{% else %}<!-- 未登录时的链接 -->{% endif %}</ul></div></div></div>
</footer>
- 样式文件:staticfiles/admin/css/base.css 定义了系统的全局样式,包括字体、颜色、链接样式等。通过 CSS 变量的使用,提高了样式的可维护性。
:root {--font-family-primary:system-ui,-apple-system,"Segoe UI",system-ui,Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-family-monospace:ui-monospace,Menlo,Monaco,"Cascadia Mono","Segoe UI Mono","Roboto Mono","Oxygen Mono","Ubuntu Monospace","Source Code Pro","Fira Mono","Droid Sans Mono","Courier New",monospace,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";color-scheme: light;
}
2.3 交互功能
前端的交互功能主要通过 Django 的模板标签和表单实现。例如,在结账视图中,用户可以选择地址、使用优惠券等,这些操作通过表单提交到后端进行处理。
三、后端分析
3.1 框架选择
该系统使用 Django 作为后端框架,Django 是一个功能强大的 Python Web 框架,提供了丰富的内置功能,如用户认证、数据库管理、表单处理等,能够提高开发效率和代码的可维护性。
3.2 功能模块
- 认证系统:auth_fix.py 负责检查认证相关数据表结构并修复必要的问题,确保系统的认证功能正常运行。同时,通过 Django 的内置认证模块,实现了用户的注册、登录和注销等功能。
def check_auth_tables():"""检查认证相关数据表结构并修复必要的问题"""with connection.cursor() as cursor:# 检查django_session表是否存在cursor.execute("SHOW TABLES LIKE 'django_session'")if not cursor.fetchone():print("创建django_session表...")cursor.execute("""CREATE TABLE IF NOT EXISTS `django_session` (`session_key` varchar(40) NOT NULL,`session_data` longtext NOT NULL,`expire_date` datetime(6) NOT NULL,PRIMARY KEY (`session_key`),KEY `django_session_expire_date_a5c62663` (`expire_date`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;""")# 其他认证相关表的检查和创建# 验证认证系统连接from django.contrib.auth import get_user_modelUser = get_user_model()print(f"当前认证用户模型: {User.__name__}")print(f"系统中的用户数量: {User.objects.count()}")# 验证session表from django.contrib.sessions.models import Sessionprint(f"系统中的会话数量: {Session.objects.count()}")print("认证系统检查完成!")
- 订单管理:
orders
应用负责订单的创建、处理和管理。orders/models.py 定义了订单模型,包括订单状态、支付方式、订单金额等信息;orders/views.py 实现了结账视图,处理用户的结账请求。
class Order(models.Model):"""订单模型"""ORDER_STATUS_CHOICES = (('pending', '待付款'),('paid', '已付款'),('processing', '处理中'),('shipped', '已发货'),('delivered', '已送达'),('completed', '已完成'),('cancelled', '已取消'),('refunded', '已退款'),)PAYMENT_METHOD_CHOICES = (('alipay', '支付宝'),('wechat', '微信支付'),('credit_card', '信用卡'),('bank_transfer', '银行转账'),('cash_on_delivery', '货到付款'),)# 订单字段定义def save(self, *args, **kwargs):if not self.order_number:self.order_number = self.generate_order_number()super().save(*args, **kwargs)def generate_order_number(self):"""生成唯一的订单编号"""from django.utils import timezonenow = timezone.now()year = now.strftime('%Y')month = now.strftime('%m')day = now.strftime('%d')return f"{year}{month}{day}-{uuid.uuid4().hex[:8].upper()}"
@login_required
def checkout(request):"""结账视图"""# 获取购物车cart = request.cart# 检查购物车是否为空if cart.items.count() == 0:messages.error(request, '您的购物车为空,请先添加商品。')return redirect('cart_detail')# 获取用户地址addresses = request.user.addresses.all()# 处理优惠券coupon_form = CouponForm()coupon = Noneif 'coupon_id' in request.session:try:coupon = Coupon.objects.get(id=request.session['coupon_id'])except Coupon.DoesNotExist:coupon = None# 计算订单金额subtotal = cart.get_total_priceshipping_fee = Decimal('10.00') # 使用Decimal类型# 计算折扣discount = Decimal('0')if coupon and coupon.is_valid:if coupon.discount_type == 'percentage':discount = subtotal * (coupon.discount_value / Decimal('100'))else:discount = coupon.discount_value# 计算总金额total = subtotal + shipping_fee - discountcontext = {'cart': cart,'addresses': addresses,'coupon_form': coupon_form,'coupon': coupon,'subtotal': subtotal,'shipping_fee': shipping_fee,'discount': discount,'total': total,}return render(request, 'orders/checkout.html', context)
- 产品管理:
products
应用负责产品的管理,包括产品的添加、展示和详情页等功能。products/models.py 定义了产品模型,包含产品的基本信息和价格等。
class Product(models.Model):"""产品模型"""category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')name = models.CharField(_('产品名称'), max_length=200)slug = models.SlugField(_('产品别名'), max_length=220, unique=True)description = models.TextField(_('产品描述'))price = models.DecimalField(_('产品价格'), max_digits=10, decimal_places=2)discount_price = models.DecimalField(_('折扣价格'), max_digits=10, decimal_places=2, blank=True, null=True)stock = models.PositiveIntegerField(_('库存数量'), default=0)sales = models.PositiveIntegerField(_('销量'), default=0)is_available = models.BooleanField(_('是否可用'), default=True)is_featured = models.BooleanField(_('是否推荐'), default=False)is_new = models.BooleanField(_('是否新品'), default=False)member_only = models.BooleanField(_('会员专享'), default=False)sku = models.CharField(_('SKU'), max_length=100, unique=True)created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)updated_at = models.DateTimeField(_('更新时间'), auto_now=True)def save(self, *args, **kwargs):if not self.slug:self.slug = slugify(self.name)super().save(*args, **kwargs)@propertydef get_display_price(self):return self.discount_price if self.discount_price else self.price@propertydef discount_percentage(self):if self.discount_price:return int(((self.price - self.discount_price) / self.price) * 100)return 0@propertydef main_image(self):if self.images.exists():return self.images.first().image.urlreturn Nonedef get_absolute_url(self):from django.urls import reversereturn reverse('product_detail', args=[self.slug])
3.3 中间件
系统中使用了多个中间件,如 SessionMiddleware
用于处理用户会话,AuthenticationMiddleware
用于用户认证,CartMiddleware
用于处理购物车逻辑。这些中间件在请求处理过程中发挥了重要作用,提高了系统的安全性和用户体验。
四、数据库分析
4.1 数据库选择
系统使用 MySQL 作为数据库,通过 Django 的数据库配置文件 shopping_system/settings.py 进行数据库连接的配置。
DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql','NAME': 'shopping_system','USER': 'root','PASSWORD': 'root','HOST': '127.0.0.1','PORT': '3306','OPTIONS': {'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",'charset': 'utf8mb4',},}
}
4.2 数据表结构
- 用户相关表:
users_customuser
表存储用户的基本信息,如用户名、密码、邮箱等;users_userprofile
表存储用户的详细资料,如出生日期、性别等;users_address
表存储用户的收货地址信息。
-- 用户表
CREATE TABLE `users_customuser` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`password` varchar(128) NOT NULL,`last_login` datetime DEFAULT NULL,`is_superuser` tinyint(1) NOT NULL,`first_name` varchar(150) NOT NULL,`last_name` varchar(150) NOT NULL,`is_staff` tinyint(1) NOT NULL,`is_active` tinyint(1) NOT NULL,`date_joined` datetime NOT NULL,`email` varchar(254) NOT NULL UNIQUE,`username` varchar(150) NOT NULL UNIQUE,`user_type` varchar(10) NOT NULL,`phone` varchar(15) DEFAULT NULL,`address` text DEFAULT NULL,`avatar` varchar(100) DEFAULT NULL,`is_member` tinyint(1) NOT NULL,`member_since` datetime DEFAULT NULL,`member_expire` datetime DEFAULT NULL,`points` int(11) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 用户资料表
CREATE TABLE `users_userprofile` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`birth_date` date DEFAULT NULL,`gender` varchar(10) DEFAULT NULL,`bio` text DEFAULT NULL,`created_at` datetime NOT NULL,`updated_at` datetime NOT NULL,`user_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `user_id` (`user_id`),CONSTRAINT `fk_userprofile_user` FOREIGN KEY (`user_id`) REFERENCES `users_customuser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 地址表
CREATE TABLE `users_address` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`receiver` varchar(100) NOT NULL,`phone` varchar(15) NOT NULL,`province` varchar(100) NOT NULL,`city` varchar(100) NOT NULL,`district` varchar(100) NOT NULL,`address` varchar(200) NOT NULL,`zipcode` varchar(10) DEFAULT NULL,`is_default` tinyint(1) NOT NULL,`user_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `user_id` (`user_id`),CONSTRAINT `fk_address_user` FOREIGN KEY (`user_id`) REFERENCES `users_customuser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
- 产品相关表:
products_category
表存储产品的分类信息;products_product
表存储产品的基本信息;products_productspecification
表存储产品的规格信息;products_review
表存储产品的评论信息;products_reviewimage
表存储评论的图片信息。
-- 产品类别表
CREATE TABLE `products_category` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`name` varchar(100) NOT NULL,`slug` varchar(120) NOT NULL UNIQUE,`description` text DEFAULT NULL,`image` varchar(100) DEFAULT NULL,`is_active` tinyint(1) NOT NULL,`created_at` datetime NOT NULL,`updated_at` datetime NOT NULL,`parent_id` bigint(20) DEFAULT NULL,PRIMARY KEY (`id`),KEY `parent_id` (`parent_id`),CONSTRAINT `fk_category_parent` FOREIGN KEY (`parent_id`) REFERENCES `products_category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 产品表
CREATE TABLE `products_product` (`id` bigint(20) NOT NULL AUTO_INCREMENT,-- 产品字段定义
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 产品规格表
CREATE TABLE `products_productspecification` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`name` varchar(100) NOT NULL,`value` varchar(100) NOT NULL,`product_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `product_id` (`product_id`),CONSTRAINT `fk_specification_product` FOREIGN KEY (`product_id`) REFERENCES `products_product` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 产品评论表
CREATE TABLE `products_review` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`rating` int(11) NOT NULL,`title` varchar(100) DEFAULT NULL,`comment` text NOT NULL,`is_anonymous` tinyint(1) NOT NULL,`created_at` datetime NOT NULL,`product_id` bigint(20) NOT NULL,`user_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `product_id` (`product_id`),KEY `user_id` (`user_id`),CONSTRAINT `fk_review_product` FOREIGN KEY (`product_id`) REFERENCES `products_product` (`id`),CONSTRAINT `fk_review_user` FOREIGN KEY (`user_id`) REFERENCES `users_customuser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 评论图片表
CREATE TABLE `products_reviewimage` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`image` varchar(100) NOT NULL,`review_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `review_id` (`review_id`),CONSTRAINT `fk_reviewimage_review` FOREIGN KEY (`review_id`) REFERENCES `products_review` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
- 订单相关表:
orders_order
表存储订单的基本信息;orders_orderitem
表存储订单项的信息;orders_payment
表存储支付记录的信息;orders_shipment
表存储物流记录的信息。
-- 订单表
CREATE TABLE `orders_order` (`id` bigint(20) NOT NULL AUTO_INCREMENT,-- 订单字段定义PRIMARY KEY (`id`),KEY `address_id` (`address_id`),KEY `coupon_id` (`coupon_id`),KEY `user_id` (`user_id`),CONSTRAINT `fk_order_address` FOREIGN KEY (`address_id`) REFERENCES `users_address` (`id`),CONSTRAINT `fk_order_coupon` FOREIGN KEY (`coupon_id`) REFERENCES `orders_coupon` (`id`),CONSTRAINT `fk_order_user` FOREIGN KEY (`user_id`) REFERENCES `users_customuser` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 订单项表
CREATE TABLE `orders_orderitem` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`quantity` int(10) unsigned NOT NULL,`price` decimal(10,2) NOT NULL,`total` decimal(10,2) NOT NULL,`order_id` bigint(20) NOT NULL,`product_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `order_id` (`order_id`),KEY `product_id` (`product_id`),CONSTRAINT `fk_orderitem_order` FOREIGN KEY (`order_id`) REFERENCES `orders_order` (`id`),CONSTRAINT `fk_orderitem_product` FOREIGN KEY (`product_id`) REFERENCES `products_product` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 支付记录表
CREATE TABLE `orders_payment` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`payment_method` varchar(20) NOT NULL,`transaction_id` varchar(100) NOT NULL,`amount` decimal(10,2) NOT NULL,`status` varchar(20) NOT NULL,`created_at` datetime NOT NULL,`updated_at` datetime NOT NULL,`order_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `order_id` (`order_id`),CONSTRAINT `fk_payment_order` FOREIGN KEY (`order_id`) REFERENCES `orders_order` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
-- 物流记录表
CREATE TABLE `orders_shipment` (`id` bigint(20) NOT NULL AUTO_INCREMENT,`tracking_number` varchar(100) NOT NULL,`carrier` varchar(100) NOT NULL,`status` varchar(20) NOT NULL,`shipped_at` datetime DEFAULT NULL,`delivered_at` datetime DEFAULT NULL,`order_id` bigint(20) NOT NULL,PRIMARY KEY (`id`),KEY `order_id` (`order_id`),CONSTRAINT `fk_shipment_order` FOREIGN KEY (`order_id`) REFERENCES `orders_order` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
4.3 数据插入
test.sql 文件中包含了部分数据表的数据插入语句,用于测试和初始化数据库。例如,插入产品信息、订单项信息、支付记录信息和物流记录信息等。
-- 产品表数据插入
INSERT INTO `products_product`
(`name`, `slug`, `description`, `price`, `discount_price`, `stock`, `sales`, `is_available`, `is_featured`, `is_new`, `member_only`, `sku`, `created_at`, `updated_at`, `category_id`)
VALUES
-- 智能手机
('超级智能手机X', 'smart-phone-x', '最新款智能手机,配备顶级摄像头', 3999.00, 3799.00, 100, 50, 1, 1, 1, 0,
'SP-001', '2023-01-01 00:00:00', '2023-05-31 00:00:00', 5),
-- 其他产品信息...
-- 订单项表数据插入
INSERT INTO `orders_orderitem`
(`quantity`, `price`, `total`, `order_id`, `product_id`)
VALUES
(1, 3999.00, 3999.00, 1, 1);
-- 支付记录表数据插入
INSERT INTO `orders_payment`
(`payment_method`, `transaction_id`, `amount`, `status`, `created_at`, `updated_at`, `order_id`)
VALUES
('alipay', 'ALI123456789', 3799.00, 'completed', '2023-05-01 00:05:00', '2023-05-01 00:05:30', 1);
-- 物流记录表数据插入
INSERT INTO `orders_shipment`
(`tracking_number`, `carrier`, `status`, `shipped_at`, `delivered_at`, `order_id`)
VALUES
('SF1234567890', '顺丰速运', 'delivered', '2023-05-02 09:00:00', '2023-05-05 14:00:00', 1);
五、总结
本购物系统通过 Django 框架实现了一个完整的电商平台,前端提供了良好的用户界面和交互体验,后端实现了各种业务逻辑和功能模块,数据库设计合理,能够满足系统的数据存储和管理需求。然而,系统仍有一些可以改进的地方,如前端的响应式设计、性能优化,后端的缓存机制和并发处理等,以提高系统的可用性和性能。
源码下载
链接:https://pan.quark.cn/s/1c46086175f3