Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django篮子中产品的数量(按产品ID)_Python_Django - Fatal编程技术网

Python Django篮子中产品的数量(按产品ID)

Python Django篮子中产品的数量(按产品ID),python,django,Python,Django,尝试按特定的产品ID计算购物车中的物品数量,但遇到困难,例如,篮子中有7个苹果。我一直在尝试使用python count函数,但目前不起作用。我尝试将以下代码添加到我的cart.py文件中,但无效: def count_prod(self, product) product_id = str(product.id) if product_id in self.cart: return count(self.cart[product_id]) 这是我的cart.py文件 from

尝试按特定的产品ID计算购物车中的物品数量,但遇到困难,例如,篮子中有7个苹果。我一直在尝试使用python count函数,但目前不起作用。我尝试将以下代码添加到我的cart.py文件中,但无效:

def count_prod(self, product)
product_id = str(product.id)
  if product_id in self.cart:
      return count(self.cart[product_id])
这是我的cart.py文件

from decimal import Decimal
from django.conf import settings
from shop.models import Product


class Cart(object):

    def __init__(self, request):
        """
        Initialize the cart.
        """
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            # save an empty cart in the session
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def __len__(self):
        """
        Count all items in the cart.
        """
        return sum(item['quantity'] for item in self.cart.values())

    def __iter__(self):
        """
        Iterate over the items in the cart and get the products from the database.
        """
        product_ids = self.cart.keys()
        # get the product objects and add them to the cart
        products = Product.objects.filter(id__in=product_ids)
        for product in products:
            self.cart[str(product.id)]['product'] = product

        for item in self.cart.values():
            item['price'] = Decimal(item['price'])
            item['total_price'] = item['price'] * item['quantity']
            yield item

    def add(self, product, quantity=1, update_quantity=False):
        """
        Add a product to the cart or update its quantity.
        """
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'quantity': 0,
                                      'price': str(product.price)}
        if update_quantity:
            self.cart[product_id]['quantity'] = quantity
        else:
            self.cart[product_id]['quantity'] += quantity
        self.save()

    def remove(self, product):
        """
        Remove a product from the cart.
        """
        product_id = str(product.id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def save(self):
        # update the session cart
        self.session[settings.CART_SESSION_ID] = self.cart
        # mark the session as "modified" to make sure it is saved
        self.session.modified = True

    def clear(self):
        # empty cart
        self.session[settings.CART_SESSION_ID] = {}
        self.session.modified = True

    def get_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
Views.py文件:

from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from shop.models import Product
from .cart import Cart
from .forms import CartAddProductForm


@require_POST
def cart_add(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    form = CartAddProductForm(request.POST)
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(product=product,
                #  quantity=cd['quantity'],
                 update_quantity=cd['update'])
    return redirect(product.category.get_absolute_url())


def cart_remove(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)
    cart.remove(product)
    return redirect('cart:cart_detail')


def cart_detail(request):
    cart = Cart(request)
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'],
                                                                   'update': True})
    return render(request, 'cart/detail.html', {'cart': cart})

感谢您的帮助

Your
self.cart[product\u id]
是一本字典,其形式如下:

{'quantity': 5,
 'price': '1.50'}
因此,如果您想要项目的数量,只需检查
数量

if product_id in self.cart:
    self.cart['product_id']['quantity']

您的
self.cart[product\u id]
是以下形式的词典:

{'quantity': 5,
 'price': '1.50'}
因此,如果您想要项目的数量,只需检查
数量

if product_id in self.cart:
    self.cart['product_id']['quantity']

谢谢,这在我的cart.py文件中。我如何从我的模板中引用这个方法?我必须使用视图吗?这是一个单独的问题,所以我无法帮助。在视图中调用该方法并将其传递给模板可能会更容易。谢谢,这在my cart.py文件中。我如何从我的模板中引用这个方法?我必须使用视图吗?这是一个单独的问题,所以我无法帮助。在视图中调用该方法并将其传递给模板可能会更容易。