Django支付时触发productId KeyError,购物车数量未更新问题
Django购物车支付异常问题解决
问题原因
- 支付操作错误调用了负责商品增减的
updateItem接口,且请求体中未携带productId字段,直接通过data['productId']取值触发KeyError。 - 支付逻辑与商品数量修改逻辑混同,未单独处理订单完成流程,导致购物车数量无法更新。
解决方案
1. 拆分接口职责,新增支付处理视图
updateItem仅用于处理购物车商品的增减,支付逻辑单独编写在新视图中:
def processPayment(request): customer = request.user.customer try: order = Order.objects.get(customer=customer, complete=False) except Order.DoesNotExist: return JsonResponse('No active order found', status=404, safe=False) # 此处添加实际支付逻辑(如调用第三方支付API) # 支付成功后标记订单为已完成 order.complete = True order.save() return JsonResponse('Payment completed', safe=False)
2. 给updateItem添加字段校验与异常处理
避免因缺少字段或商品不存在导致崩溃:
def updateItem(request): data = json.loads(request.body) # 校验必填字段 if 'productId' not in data or 'action' not in data: return JsonResponse('Missing required fields', status=400, safe=False) productId = data['productId'] action = data['action'] customer = request.user.customer # 处理商品不存在的情况 try: product = Product.objects.get(id=productId) except Product.DoesNotExist: return JsonResponse('Product not found', status=404, safe=False) 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 += 1 elif action == 'remove': orderItem.quantity -= 1 # 处理数量为0的情况 if orderItem.quantity <= 0: orderItem.delete() else: orderItem.save() return JsonResponse('Item updated', safe=False)
3. 调整前端逻辑
- 支付按钮点击时,调用
processPayment接口而非updateItem。 - 支付成功后,前端刷新购物车数据(或直接清空购物车显示),确保数量同步更新。
内容的提问来源于stack exchange,提问作者Sasivardhan Bonthu
相关产品推荐
相关产品推荐

