【问题标题】:AttributeError when adding an item to a basket将商品添加到购物篮时出现 AttributeError
【发布时间】: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


【解决方案1】:

您的 Basket 类的 add 方法包含以下行:

self.save()

但是,Basket 类目前没有实现方法save。它也不从任何父类继承它。

add 方法尝试执行未定义的类方法这一事实解释了您的属性错误。

【讨论】:

    猜你喜欢
    • 2015-04-29
    • 2012-06-30
    • 1970-01-01
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多