【发布时间】:2021-11-25 14:56:26
【问题描述】:
我一直想弄清楚为什么 Django 在尝试将物品添加到购物篮时会抛出这个 AttributeError。
错误如下所示:
AttributeError: 'Basket' object has no attribute 'save'
我浏览了我的代码,但似乎找不到问题所在。我已经在下面发布了必要的代码。
basket/basket.py:
class Basket():
def __init__(self, request):
self.session = request.session
basket = self.session.get('skey')
if 'skey' not in request.session:
basket = self.session['skey'] = {}
self.basket = basket
def add(self, product, qty):
"""
Adding and updating the users basket session data
"""
product_id = str(product.id)
if product_id in self.basket:
self.basket[product_id]['qty'] = qty
else:
self.basket[product_id] = {'price': str(product.price), 'qty': qty}
self.save()
def __iter__(self):
"""
Collect the product_id in the session data to query the database
and return products
"""
product_ids = self.basket.keys()
products = Product.products.filter(id__in=product_ids)
basket = self.basket.copy()
for product in products:
basket[str(product.id)]['product'] = product
for item in basket.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['qty']
yield item
def __len__(self):
"""
Get the basket data and count the qty of items
"""
return sum(item['qty'] for item in self.basket.values())
basket/views.py:
def basket_summary(request):
basket = Basket(request)
return render(request, 'main_store/basket/summary.html', {'basket': basket})
def basket_add(request):
basket = Basket(request)
if request.POST.get('action') == 'post':
product_id = int(request.POST.get('productid'))
product_qty = int(request.POST.get('productqty'))
product = get_object_or_404(Product, id=product_id)
basket.add(product=product, qty=product_qty)
basketqty = basket.__len__()
response = JsonResponse({'qty': basketqty})
return response
添加产品的脚本 - single_product.html:
<script>
$(document).on('click', '#add-button', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "basket:basket_add" %}',
data: {
productid: $('#add-button').val(),
productqty: $('#select option:selected').text(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: 'post'
},
success: function (json) {
document.getElementById("basket-qty").innerHTML = json.qty
},
error: function (xhr, errmsg, err) { }
});
})
</script>
起初,我认为这可能是一个简单的案例,将名称命名为 basket 而不是大写的 Basket。但我认为问题可能比这更深。
非常感谢任何帮助,如果需要更多信息,请告诉我,我很乐意提供。谢谢!
【问题讨论】:
-
是不是像你的
Basket类没有save方法那么简单,但是你在Basket.add中调用它? -
非常感谢,Lain,我知道这一定是明显的疏忽!
标签: python django django-views django-templates