Django 5中CartItem模型quantity累加报错:proxy对象无get属性
问题解决:AttributeError(proxy对象没有get属性)
错误根源
视图最后直接返回reverse_lazy('shop:home')是错误的:reverse_lazy返回的是ReverseLazy延迟对象,并非Django视图要求的HttpResponse类型,Django尝试处理该对象时触发了"proxy对象没有get属性"的异常。
修复方案
- 导入Django的
redirect快捷函数 - 将返回语句替换为生成合法HTTP重定向响应的代码,同时移除无用的
model = Product属性(View基类不需要该配置)
修正后的完整视图代码
from django.shortcuts import get_object_or_404, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.views import View from .models import Product, Cart, CartItem class AddToCartView(LoginRequiredMixin, View): def post(self, request, *args, **kwargs): product = get_object_or_404(Product, pk=kwargs['pk']) cart, created = Cart.objects.get_or_create(user=request.user) cart_item, created = CartItem.objects.get_or_create(cart=cart, product=product) quantity = request.POST.get('quantity') try: quantity = int(quantity) if quantity else 1 except ValueError: quantity = 1 cart_item.quantity += quantity cart_item.save() return redirect('shop:home')
额外检查点
- 确认
Cart模型不是代理模型(代理模型无法拥有user这类额外字段,若误设proxy=True会导致异常) - 确保
LoginRequiredMixin已正确验证用户登录状态(当前代码已配置,无需额外操作)
内容的提问来源于stack exchange,提问作者user2380354
相关产品推荐
相关产品推荐

