国产亚洲精品福利在线无卡一,国产精久久一区二区三区,亚洲精品无码国模,精品久久久久久无码专区不卡

當(dāng)前位置: 首頁 > news >正文

萬網(wǎng)網(wǎng)站模板下載seo指的是搜索引擎

萬網(wǎng)網(wǎng)站模板下載,seo指的是搜索引擎,網(wǎng)站加密傳輸怎么做,富陽區(qū)建設(shè)工程質(zhì)監(jiān)站網(wǎng)站實(shí)操在線商城 一、今日學(xué)習(xí)內(nèi)容概述 模塊重要程度主要內(nèi)容商品模型?????商品信息、分類管理購物車系統(tǒng)?????購物車功能實(shí)現(xiàn)訂單系統(tǒng)?????訂單處理、支付集成用戶中心????訂單管理、個人信息 二、模型設(shè)計 # models.py from django.db import models fro…

實(shí)操在線商城

一、今日學(xué)習(xí)內(nèi)容概述

模塊重要程度主要內(nèi)容
商品模型?????商品信息、分類管理
購物車系統(tǒng)?????購物車功能實(shí)現(xiàn)
訂單系統(tǒng)?????訂單處理、支付集成
用戶中心????訂單管理、個人信息

二、模型設(shè)計

# models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from decimal import Decimalclass Category(models.Model):name = models.CharField('分類名稱', max_length=100)slug = models.SlugField('URL', unique=True)description = models.TextField('描述', blank=True)image = models.ImageField('分類圖片', upload_to='categories/', blank=True)class Meta:verbose_name = '商品分類'verbose_name_plural = verbose_namedef __str__(self):return self.nameclass Product(models.Model):category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='products')name = models.CharField('商品名稱', max_length=200)slug = models.SlugField('URL', unique=True)description = models.TextField('商品描述')price = models.DecimalField('價格', max_digits=10, decimal_places=2)stock = models.PositiveIntegerField('庫存')available = models.BooleanField('是否可用', default=True)created = models.DateTimeField('創(chuàng)建時間', auto_now_add=True)updated = models.DateTimeField('更新時間', auto_now=True)image = models.ImageField('商品圖片', upload_to='products/')class Meta:verbose_name = '商品'verbose_name_plural = verbose_nameordering = ['-created']def __str__(self):return self.nameclass Cart(models.Model):user = models.OneToOneField(User, on_delete=models.CASCADE)created = models.DateTimeField('創(chuàng)建時間', auto_now_add=True)updated = models.DateTimeField('更新時間', auto_now=True)class Meta:verbose_name = '購物車'verbose_name_plural = verbose_namedef get_total_price(self):return sum(item.get_cost() for item in self.items.all())class CartItem(models.Model):cart = models.ForeignKey(Cart, related_name='items', on_delete=models.CASCADE)product = models.ForeignKey(Product, on_delete=models.CASCADE)quantity = models.PositiveIntegerField('數(shù)量', default=1)class Meta:verbose_name = '購物車項(xiàng)目'verbose_name_plural = verbose_namedef get_cost(self):return self.product.price * self.quantityclass Order(models.Model):STATUS_CHOICES = [('pending', '待支付'),('paid', '已支付'),('shipped', '已發(fā)貨'),('completed', '已完成'),('cancelled', '已取消'),]user = models.ForeignKey(User, on_delete=models.CASCADE)address = models.TextField('收貨地址')phone = models.CharField('聯(lián)系電話', max_length=20)total_amount = models.DecimalField('總金額', max_digits=10, decimal_places=2)status = models.CharField('訂單狀態(tài)', max_length=10, choices=STATUS_CHOICES, default='pending')created = models.DateTimeField('創(chuàng)建時間', auto_now_add=True)updated = models.DateTimeField('更新時間', auto_now=True)class Meta:verbose_name = '訂單'verbose_name_plural = verbose_nameordering = ['-created']def __str__(self):return f'Order {self.id}'class OrderItem(models.Model):order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)product = models.ForeignKey(Product, on_delete=models.CASCADE)price = models.DecimalField('價格', max_digits=10, decimal_places=2)quantity = models.PositiveIntegerField('數(shù)量', default=1)class Meta:verbose_name = '訂單項(xiàng)目'verbose_name_plural = verbose_namedef get_cost(self):return self.price * self.quantity

三、視圖實(shí)現(xiàn)

# views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .models import Product, Cart, CartItem, Order, OrderItemdef product_list(request, category_slug=None):category = Nonecategories = Category.objects.all()products = Product.objects.filter(available=True)if category_slug:category = get_object_or_404(Category, slug=category_slug)products = products.filter(category=category)return render(request, 'shop/product_list.html', {'category': category,'categories': categories,'products': products})@login_required
def add_to_cart(request, product_id):product = get_object_or_404(Product, id=product_id)cart, created = Cart.objects.get_or_create(user=request.user)cart_item, item_created = CartItem.objects.get_or_create(cart=cart,product=product)if not item_created:cart_item.quantity += 1cart_item.save()messages.success(request, f'{product.name} 已添加到購物車')return redirect('cart_detail')@login_required
def cart_detail(request):cart, created = Cart.objects.get_or_create(user=request.user)return render(request, 'shop/cart_detail.html', {'cart': cart})@login_required
def checkout(request):cart = get_object_or_404(Cart, user=request.user)if request.method == 'POST':# 創(chuàng)建訂單order = Order.objects.create(user=request.user,address=request.POST.get('address'),phone=request.POST.get('phone'),total_amount=cart.get_total_price())# 創(chuàng)建訂單項(xiàng)目for item in cart.items.all():OrderItem.objects.create(order=order,product=item.product,price=item.product.price,quantity=item.quantity)# 清空購物車cart.items.all().delete()messages.success(request, '訂單創(chuàng)建成功!')return redirect('order_detail', order_id=order.id)return render(request, 'shop/checkout.html', {'cart': cart})

四、購物車流程圖

在這里插入圖片描述

五、模板實(shí)現(xiàn)

<!-- templates/shop/product_list.html -->
{% extends "base.html" %}{% block content %}
<div class="container mt-4"><div class="row"><!-- 分類側(cè)邊欄 --><div class="col-md-3"><div class="list-group"><a href="{% url 'product_list' %}" class="list-group-item list-group-item-action">所有商品</a>{% for c in categories %}<a href="{{ c.get_absolute_url }}" class="list-group-item list-group-item-action">{{ c.name }}</a>{% endfor %}</div></div><!-- 商品列表 --><div class="col-md-9"><div class="row">{% for product in products %}<div class="col-md-4 mb-4"><div class="card"><img src="{{ product.image.url }}" class="card-img-top" alt="{{ product.name }}"><div class="card-body"><h5 class="card-title">{{ product.name }}</h5><p class="card-text">價格: ¥{{ product.price }}</p><form action="{% url 'add_to_cart' product.id %}" method="post">{% csrf_token %}<button type="submit" class="btn btn-primary">加入購物車</button></form></div></div></div>{% endfor %}</div></div></div>
</div>
{% endblock %}<!-- templates/shop/cart_detail.html -->
{% extends "base.html" %}{% block content %}
<div class="container mt-4"><h2>購物車</h2>{% if cart.items.all %}<table class="table"><thead><tr><th>商品</th><th>單價</th><th>數(shù)量</th><th>小計</th><th>操作</th></tr></thead><tbody>{% for item in cart.items.all %}<tr><td>{{ item.product.name }}</td><td>¥{{ item.product.price }}</td><td>{{ item.quantity }}</td><td>¥{{ item.get_cost }}</td><td><form action="{% url 'remove_from_cart' item.id %}" method="post">{% csrf_token %}<button type="submit" class="btn btn-danger btn-sm">刪除</button></form></td></tr>{% endfor %}</tbody><tfoot><tr><td colspan="3"><strong>總計</strong></td><td><strong>¥{{ cart.get_total_price }}</strong></td><td></td></tr></tfoot></table><a href="{% url 'checkout' %}" class="btn btn-primary">去結(jié)算</a>{% else %}<p>購物車是空的。</p>{% endif %}
</div>
{% endblock %}

六、URL配置

# urls.py
from django.urls import path
from . import viewsurlpatterns = [path('', views.product_list, name='product_list'),path('category/<slug:category_slug>/', views.product_list, name='product_list_by_category'),path('product/<int:id>/<slug:slug>/', views.product_detail, name='product_detail'),path('cart/', views.cart_detail, name='cart_detail'),path('add/<int:product_id>/',views.add_to_cart,name='add_to_cart'),path('remove/<int:item_id>/',views.remove_from_cart,name='remove_from_cart'),path('checkout/',views.checkout,name='checkout'),path('orders/',views.order_list,name='order_list'),path('order/<int:order_id>/',views.order_detail,name='order_detail'),
]

七、訂單處理

# services.py
from django.db import transaction
from .models import Order, OrderItem, Cartclass OrderService:@staticmethod@transaction.atomicdef create_order(user, address, phone):"""創(chuàng)建訂單"""cart = Cart.objects.get(user=user)# 檢查庫存for item in cart.items.all():if item.quantity > item.product.stock:raise ValueError(f'{item.product.name} 庫存不足')# 創(chuàng)建訂單order = Order.objects.create(user=user,address=address,phone=phone,total_amount=cart.get_total_price())# 創(chuàng)建訂單項(xiàng)目并更新庫存for item in cart.items.all():OrderItem.objects.create(order=order,product=item.product,price=item.product.price,quantity=item.quantity)item.product.stock -= item.quantityitem.product.save()# 清空購物車cart.items.all().delete()return order

八、測試代碼

# tests.py
from django.test import TestCase
from django.contrib.auth.models import User
from .models import Product, Cart, CartItem
from decimal import Decimalclass ShopTest(TestCase):def setUp(self):self.user = User.objects.create_user(username='testuser',password='testpass123')self.product = Product.objects.create(name='Test Product',price=Decimal('99.99'),stock=10)def test_add_to_cart(self):self.client.login(username='testuser', password='testpass123')response = self.client.post(f'/add/{self.product.id}/')self.assertEqual(response.status_code, 302)cart = Cart.objects.get(user=self.user)self.assertEqual(cart.items.count(), 1)# tests.py def test_checkout(self):self.client.login(username='testuser', password='testpass123')# 添加商品到購物車cart = Cart.objects.create(user=self.user)CartItem.objects.create(cart=cart,product=self.product,quantity=2)# 提交訂單response = self.client.post('/checkout/', {'address': 'Test Address','phone': '1234567890'})self.assertEqual(response.status_code, 302)self.assertEqual(cart.items.count(), 0)  # 購物車已清空# 檢查訂單是否創(chuàng)建成功order = Order.objects.filter(user=self.user).first()self.assertIsNotNone(order)self.assertEqual(order.total_amount, Decimal('199.98'))def test_stock_management(self):"""測試庫存管理"""self.client.login(username='testuser', password='testpass123')# 添加超出庫存數(shù)量的商品cart = Cart.objects.create(user=self.user)CartItem.objects.create(cart=cart,product=self.product,quantity=15  # 大于庫存)# 嘗試結(jié)算response = self.client.post('/checkout/', {'address': 'Test Address','phone': '1234567890'})# 應(yīng)該返回錯誤self.assertEqual(response.status_code, 400)self.assertIn('庫存不足', response.content.decode())

九、支付集成

# payment.py
from decimal import Decimal
import stripe
from django.conf import settingsstripe.api_key = settings.STRIPE_SECRET_KEYclass PaymentService:@staticmethoddef create_payment_intent(order):"""創(chuàng)建支付意圖"""try:intent = stripe.PaymentIntent.create(amount=int(order.total_amount * 100),  # 轉(zhuǎn)換為分currency='cny',metadata={'order_id': order.id})return intent.client_secretexcept stripe.error.StripeError as e:raise ValueError(f"支付創(chuàng)建失敗: {str(e)}")@staticmethoddef confirm_payment(payment_intent_id):"""確認(rèn)支付"""try:intent = stripe.PaymentIntent.retrieve(payment_intent_id)return intent.status == 'succeeded'except stripe.error.StripeError as e:raise ValueError(f"支付確認(rèn)失敗: {str(e)}")# views.py 添加支付相關(guān)視圖
@login_required
def payment_process(request, order_id):order = get_object_or_404(Order, id=order_id, user=request.user)if request.method == 'POST':# 創(chuàng)建支付意圖try:client_secret = PaymentService.create_payment_intent(order)return render(request, 'shop/payment.html', {'client_secret': client_secret,'order': order,'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY})except ValueError as e:messages.error(request, str(e))return redirect('order_detail', order_id=order.id)return render(request, 'shop/payment.html', {'order': order})

十、異步任務(wù)處理

# tasks.py
from celery import shared_task
from django.core.mail import send_mail
from .models import Order@shared_task
def send_order_confirmation(order_id):"""發(fā)送訂單確認(rèn)郵件"""order = Order.objects.get(id=order_id)subject = f'訂單確認(rèn) #{order.id}'message = f'''親愛的 {order.user.username}:您的訂單 #{order.id} 已確認(rèn)。訂單總金額:¥{order.total_amount}感謝您的購買!'''send_mail(subject,message,'noreply@example.com',[order.user.email],fail_silently=False,)@shared_task
def check_order_timeout():"""檢查超時未支付訂單"""from django.utils import timezonefrom datetime import timedeltatimeout = timezone.now() - timedelta(hours=24)orders = Order.objects.filter(status='pending',created__lt=timeout)for order in orders:order.status = 'cancelled'order.save()

十一、性能優(yōu)化建議

  1. 查詢優(yōu)化

    • 使用select_related和prefetch_related
    • 添加適當(dāng)?shù)乃饕?/li>
    • 緩存熱門商品
  2. 緩存策略

    • 緩存商品列表
    • 緩存分類信息
    • 使用頁面緩存
  3. 異步處理

    • 郵件發(fā)送
    • 訂單狀態(tài)更新
    • 庫存檢查
  4. 前端優(yōu)化

    • 圖片懶加載
    • 靜態(tài)資源壓縮
    • AJAX局部刷新

十二、擴(kuò)展功能建議

  1. 商品功能

    • 商品評價系統(tǒng)
    • 商品收藏
    • 商品推薦
  2. 訂單功能

    • 訂單跟蹤
    • 訂單導(dǎo)出
    • 退換貨處理
  3. 用戶功能

    • 會員等級
    • 積分系統(tǒng)
    • 優(yōu)惠券
  4. 統(tǒng)計分析

    • 銷售報表
    • 用戶行為分析
    • 庫存預(yù)警

怎么樣今天的內(nèi)容還滿意嗎?再次感謝朋友們的觀看,關(guān)注GZH:凡人的AI工具箱,回復(fù)666,送您價值199的AI大禮包。最后,祝您早日實(shí)現(xiàn)財務(wù)自由,還請給個贊,謝謝!

http://m.aloenet.com.cn/news/31638.html

相關(guān)文章:

  • 定制制作網(wǎng)站價格今日頭條鄭州頭條新聞
  • 網(wǎng)站的銷售怎么做2023新一輪病毒叫什么名字
  • 海安公司網(wǎng)站建設(shè)建立網(wǎng)站需要多少錢
  • 小紅書廣告代理商志鴻優(yōu)化網(wǎng)
  • 做國外服務(wù)器網(wǎng)站嗎外鏈網(wǎng)站大全
  • 找私人做網(wǎng)站程序費(fèi)用淘寶推廣平臺有哪些
  • 織夢網(wǎng)站欄目管理空白廣州網(wǎng)站優(yōu)化公司排名
  • 羅湖網(wǎng)站建設(shè)優(yōu)化即刻搜索
  • 企業(yè)網(wǎng)站安全建設(shè)方案上海搜索引擎優(yōu)化1
  • 典型營銷型網(wǎng)站有哪些seo網(wǎng)站推廣優(yōu)化論文
  • 樣板網(wǎng)站百度推廣開戶多少錢
  • 技術(shù)支持東莞網(wǎng)站建設(shè)機(jī)械想做網(wǎng)絡(luò)推廣如何去做
  • html5 js全屏滑動網(wǎng)站源碼沈陽優(yōu)化網(wǎng)站公司
  • 有網(wǎng)站源碼怎么搭建網(wǎng)站近期國際新聞
  • 天水網(wǎng)站開發(fā)關(guān)鍵詞查詢工具
  • 去哪兒網(wǎng)站做宣傳多少錢公司快速建站
  • wordpress教程lnmp網(wǎng)站優(yōu)化什么意思
  • 張掖公司網(wǎng)站制作百度熱線人工服務(wù)電話
  • 辛集市住房和城鄉(xiāng)建設(shè)廳網(wǎng)站優(yōu)化20條措施
  • 怎么寫網(wǎng)站建設(shè)方案書鏈接提取視頻的網(wǎng)站
  • 做網(wǎng)貸網(wǎng)站多少錢百度上怎么打廣告宣傳
  • 便利的網(wǎng)站建設(shè)網(wǎng)站是如何建立的
  • 網(wǎng)站建設(shè)學(xué)習(xí)內(nèi)容網(wǎng)絡(luò)服務(wù)提供者知道或者應(yīng)當(dāng)知道
  • 建筑模板種類有哪些關(guān)鍵詞優(yōu)化公司排行
  • 深圳外貿(mào)建站網(wǎng)絡(luò)推廣價格百度快照提交入口
  • 哪里學(xué)網(wǎng)站建設(shè)與管理太原做網(wǎng)絡(luò)推廣的公司
  • 東莞橋頭網(wǎng)站設(shè)計seo關(guān)鍵詞排名優(yōu)化價格
  • 萊蕪市住房和城鄉(xiāng)建設(shè)廳網(wǎng)站軟文關(guān)鍵詞排名推廣
  • 微信小程序怎么寫寧波seo排名優(yōu)化價格
  • wordpress超鏈接代碼山東seo網(wǎng)絡(luò)推廣