未登录用户无法将商品添加至购物车问题求助
未登录用户无法将商品添加至购物车问题求助
大家好,我现在遇到一个棘手的问题:我想让未登录用户也能把商品加入购物车,但点击「加入购物车」按钮后,购物车完全没有任何变化。我已经写了后端视图、前端JS和页面模板,但未登录状态下的购物车逻辑完全不生效,求各位帮忙排查一下问题所在!
我的现有代码
1. views.py
from django.shortcuts import render from django.http import JsonResponse import json import datetime from .models import * def store(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: # 临时模拟未登录用户的空购物车 items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'store/store.html', context) def cart(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: # 临时模拟未登录用户的空购物车 items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/cart.html', context) def checkout(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: # 临时模拟未登录用户的空购物车 items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] context = {'items':items, 'order':order, 'cartItems':cartItems} return render(request, 'store/checkout.html', context) def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) if action == 'add': orderItem.quantity = (orderItem.quantity + 1) elif action == 'remove': orderItem.quantity = (orderItem.quantity - 1) orderItem.save() if orderItem.quantity <= 0: orderItem.delete() return JsonResponse('Item was added', safe=False) def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) total = float(data['form']['total']) order.transaction_id = transaction_id if total == order.get_cart_total: order.complete = True order.save() if order.shipping == True: ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], city=data['shipping']['city'], state=data['shipping']['state'], zipcode=data['shipping']['zipcode'], ) else: print('User is not logged in') return JsonResponse('Payment submitted..', safe=False)
2. cart.js
var UpdateBtns= document.getElementsByClassName('update-cart') for(i=0;i< UpdateBtns.length;i++){ UpdateBtns[i].addEventListener('click',function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId',productId,'action',action) console.log('USER:',user) updateUserOrder(productId,action) }) } function updateUserOrder(productId,action){ var url = '/update_item/' fetch(url,{ method : 'POST', headers : { 'content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId,'action':action}) }) .then((Response)=>{ return Response.json() }) .then((data) =>{ console.log('data:',data) }) }
3. checkout.html
{% extends 'shop_templates/main.html' %} {% load static%} {%block content %} <div class="row"> <div class="col-lg-6"> <div class="box-element" id="form-wrapper"> <form id="form"> {% csrf_token %} <div id="user-info"> {% if not request.user.is_authenticated %} <div class="form-field"> <input required class="form-control" type="text" name="name" placeholder="Name.."> </div> <div class="form-field"> <input required class="form-control" type="email" name="email" placeholder="Email.."> </div> {% endif %} </div> <div id="shipping-info"> <hr> <p>shipping information :</p> <div class="form-field"> <input class="form-control" type="text" name="address" placeholder="Address.."> </div> <div class="form-field"> <input class="form-control" type="text" name="city" placeholder="City.."> </div> <!-- 剩余代码未完成 --> </div> </form> </div> </div> </div> {% endblock content %}
我自己排查到的疑似问题
我发现updateItem视图完全没有处理未登录用户的逻辑!现在只有登录用户的订单关联逻辑,未登录用户的购物车只是用临时字典模拟的空数据,但点击添加按钮后,请求到update_item时会直接尝试获取request.user.customer,未登录状态下这一步肯定会报错,而且也没有用session来存储未登录用户的购物车数据。
但我不太清楚具体怎么修改才能让未登录用户的购物车正常工作,希望各位能给我一些具体的修改建议!
内容来源于stack exchange
相关产品推荐
相关产品推荐

