day53-天天生鲜项目购物车结算页面数据同步

1购物车中商品删除功能

页面重新刷新
location.href = '/cart/cart/'
页面重新加载
location.reload()

删除
function del_cart(id) {
        var csrf = $('input[name="csrfmiddlewaretoken"]').val()
        $.ajax({
            url:'/cart/del_cart/' + id + '/',
            type:'POST',
            headers:{'X-CSRFToken':csrf},
            dataType:'json',
            success:function (data) {
                删除标签
                var nodeGoods = $('#goods_'+ id)
                nodeGoods.remove()
                cart_price()
            },
            error:function (data) {
                alert('删除失败')
            }
        })
    }

视图层删除函数

    def del_cart(request, id):
    if request.method == 'POST':
         在session中删除购物车中删除的某个商品
        session_goods = request.session.get('goods')
        for re_goods in session_goods:
            if re_goods[0] == id:
                session_goods.remove(re_goods)
                break
        request.session['goods'] = session_goods
         删除数据库中对应的session中被删除的数据
        user_id = request.session.get('user_id')
        if user_id:
            ShoppingCart.objects.filter(goods_id=id, user_id=user_id).delete()
        return JsonResponse({'code': 200, 'msg': '请求成功'})

2中间件登陆校验

主要区分哪些网址需要校验,哪些不需要校验,在需要校验的强制其跳转到登陆界面进行登陆

class LoggingMiddleware(MiddlewareMixin):
    def process_request(self, request):
        user_id = request.session.get('user_id')
        path = request.path
        不需要做登陆校验的地址
        not_need_check = ['/user/register/', '/user/login/', '/goods/index/',
                          'goods/detail/.*', '/cart/.*']
        for check_path in not_need_check:
            if re.match(check_path, path):
          当前path路径为不需要做登陆校验的路由,则直接访问对应页面
                return None
        if not user_id:
      当前path路径为不需要做登陆校验的路由,则直接访问对应页面
           return HttpResponseRedirect(reverse('user:login'))

3中间件同步数据库与session中的数据

class SessionToMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        同步session中的商品信息和数据库中购物车表的商品信息
        1.判断用户是否登陆,登陆才做数据同步操作
        user_id = request.session.get('user_id')
        if user_id:
             2.同步
            2.1判断session中的商品是否存在于数据库中,如果存在,则更新
             2.2如果不存在,则创建
           2.3同步数据库的数据到session中
            session_goods = request.session.get('goods')
            if session_goods:
                 将session中的数据同步到数据库
                for se_goods in session_goods:
                    # se_goods结构为[goods_id,num,is_select]
                    cart = ShoppingCart.objects.filter(user_id=user_id, goods_id=se_goods[0]).first()
                    if cart:
                         更新商品信息
                        if cart.nums != se_goods[1] or cart.is_select != se_goods[2]:
                            cart.nums = se_goods[1]
                            cart.is_select = se_goods[2]
                            cart.save()
                    else:
                        创建
                        ShoppingCart.objects.create(user_id=user_id, goods_id=se_goods[0],
                                                    nums=se_goods[1], is_select=se_goods[2])
            同步数据库的数据到session中
            db_carts=ShoppingCart.objects.filter(user_id=user_id)
            组装多个商品格式:[[goods_id,num,is_select],[goods_id,num,is_select]]
            if db_carts:
                new_session_goods = [[cart.goods_id, cart.nums, cart.is_select] for cart in db_carts]
                request.session['goods'] = new_session_goods
        return response

4商品结算总价及小计

cart.goods_price = price;给cart添加一个小计的属性并赋值

def place_order(request):
    if request.method == 'GET':
        获取当前登陆系统的用户对象
        user = request.user
        carts = ShoppingCart.objects.filter(user=user, is_select=True).all()
        计算小计和总价
        total_price = 0
        for cart in carts:
             小计金额
            price = cart.goods.shop_price * cart.nums
            给cart添加一个小计的属性并赋值
            cart.goods_price = price
            总金额
            total_price += price
        return render(request, 'place_order.html', {'carts': carts, 'total_price': total_price, 'num': len(carts)})

你可能感兴趣的:(day53-天天生鲜项目购物车结算页面数据同步)