day53-Django项目-天天生鲜

一、购物车数据同步模块

1.定义数据同步中间件

from django.utils.deprecation import MiddlewareMixin

from carts.models import ShoppingCart


class SessionSyncMiddleware(MiddlewareMixin):

    def process_response(self, request, response):
        # 没有登录就不用做数据同步
        # 登录情况才做数据从session同步到数据库,且重新更新session数据
        user_id = request.session.get('user_id')
        if user_id:
            # 登录情况
            session_goods = request.session.get('goods')
            if session_goods:
                # 1.判断session中商品是否存在于数据库中,如果存在则更新
                # 2.如果不存在则创建
                shop_carts = ShoppingCart.objects.filter(user_id=user_id)

                # 更新购物车中的商品数量,记录更新商品的id值
                data = []
                for goods in shop_carts:
                    for se_goods in session_goods:
                        if se_goods[0] == goods.goods_id:
                            goods.nums = se_goods[1]
                            goods.save()
                            data.append(se_goods[0])

                # 添加
                session_goods_ids = [i[0] for i in session_goods]
                add_goods_ids = list(set(session_goods_ids) - set(data))
                for add_goods_id in add_goods_ids:
                    for session_good in session_goods:
                        if add_goods_id == session_good[0]:
                            ShoppingCart.objects.create(user_id=user_id, goods_id=add_goods_id, nums=session_good[1])

            # 将数据库同步到session
            new_shop_carts = ShoppingCart.objects.filter(user_id=user_id)
            session_new_goods = [[i.goods_id, i.nums, i.is_select] for i in new_shop_carts]
            request.session['goods'] = session_new_goods

        return response


二、购物车功能模块

1.在urls.py配置文件中定义路由

from django.conf.urls import url, include

from carts import views

urlpatterns = [
    # 购物车页面
    url(r'^cart/', views.cart, name='cart'),
    # 加入购物车
    url(r'^add_cart/', views.add_cart, name='add_cart'),
    # 计算购物车中的商品数量
    url('^count_cart/', views.count_cart, name='count_cart'),
    # 修改购物车中商品的勾选状态和商品属性
    url('^change_cart/', views.change_cart, name='change_cart'),
    # 删除购物车中的商品
    url('^del_cart/(\d+)/', views.del_cart, name='del_cart'),
]

2.计算购物车中的商品数量

from django.http import JsonResponse


def count_cart(request):
    if request.method == 'GET':
        session_goods = request.session.get('goods')
        count = len(session_goods) if session_goods else 0
        return JsonResponse({'code': 200, 'msg': '请求成功', 'count': count})

3.修改购物车中商品的勾选状态和商品属性

from django.http import JsonResponse


def change_cart(request):
    if request.method == 'POST':
        # 获取前端Ajax传递的goods_id,is_select,nums
        goods_id = int(request.POST.get('goods_id'))
        is_select = request.POST.get('is_select')
        nums = request.POST.get('nums')
        # 获取session中商品的信息
        session_goods = request.session.get('goods')
        for goods in session_goods:
            if goods_id == goods[0]:
                # 修改session中的商品的数量和选择状态
                goods[1] = int(nums) if nums else goods[1]
                goods[2] = int(is_select) if is_select else goods[2]
        request.session['goods'] = session_goods
        return JsonResponse({'code': 200, 'msg': '请求成功'})

4.删除购物车中的商品

from django.http import JsonResponse, HttpResponseRedirect

from carts.models import ShoppingCart


def del_cart(request, id):
    if request.method == 'GET':
        user_id = request.session.get('user_id')
        if user_id:
            # 登录情况,删除数据库中的数据
            ShoppingCart.objects.filter(user_id=user_id, goods_id=id).delete()
        # 不管登录与否,删除session中的数据
        session_goods = request.session.get('goods')
        for goods in session_goods:
            if goods[0] == int(id):
                session_goods.remove(goods)
        request.session['goods'] = session_goods
        return HttpResponseRedirect(reverse('carts:cart'))

5.购物车页面JS代码

{% extends 'base_main.html' %}

{% block title %}
    天天生鲜-购物车
{% endblock %}

{% block js %}
    {% load static %}
    
{% endblock %}

{% block search %}
    
{% endblock %}

{% block content %}
    
全部商品0
  • 商品名称
  • 商品单位
  • 商品价格
  • 数量
  • 小计
  • 操作
{% if goods_all %} {% for goods in goods_all %}
  • {{ goods.0.name }}
    {{ goods.0.shop_price }}/500g
  • 500g
  • {{ goods.0.shop_price }}元
  • + -
  • {{ goods.2 }}元
  • 删除
{% endfor %} {% endif %}
  • 全选
  • 合计(不含运费):¥42.60
    共计2件商品
  • 去结算
{% endblock %} {% block js2 %} {% csrf_token %} {% endblock %}

你可能感兴趣的:(day53-Django项目-天天生鲜)