Django无法创建删除会话/购物车中所有项目的功能

时间:2018-03-21 12:56:13

标签: django python-3.x session django-templates cart

我试图在会话中创建一个清空购物车中所有商品的功能。我有一个非常好的功能,删除单个项目,但不能让它为所有人工作。你能让我知道我做错了什么吗?谢谢!我试图创建以下功能:

  

cart.py

class Cart(object):
    ...
        def clear(self):
    self.session.cart[settings.CART_SESSION_KEY] = {}
    self.session.modified = True

在我的网址/ views /模板中调用它,如:

  

urls.py

    path('cart/clear/', Buylist_views.clear, name= 'empty_cart'),
  

views.py

    def clear(request):
    cart = Cart(request)
    cart.clear()
    return redirect('cart')
  

模板

...
<button type="submit" formaction="{% url 'empty_cart' %}">
Empty Cart </button>
      </form>

我还尝试了以下功能:

    def empty(self):
    for each in self.cart:
        del each
    self.save()

非常感谢您的见解!完整Cart.py下面:

    class Cart(object):


    def __init__(self, request):
        self.session = request.session


        if not hasattr(settings, 'CART_SESSION_KEY'):
            raise KeyNotSet('Session key identifier is missing in settings')

        if not hasattr(settings, 'PRODUCT_MODEL'):
            raise KeyNotSet('Product model is missing in settings')

        cart = self.session.get(settings.CART_SESSION_KEY)

        if not cart:
            is_model_set = hasattr(settings, 'USE_CART_MODELS')
            if is_model_set and settings.USE_CART_MODELS:
                # cart =
                pass
            else:
                cart = self.session[settings.CART_SESSION_KEY] = {}

        self.cart = cart

    def add(self, product, price, quantity=1,):
        product_id = str(product.id)
        if product_id not in self.cart:
            self.cart[product_id] = {'price': str(price), 'quantity': 0}

        self.cart[product_id]['quantity'] = int(quantity)
        self.save()



        self.cart[product_id]['quantity'] = int(quantity)
        self.save()


    def save(self):
        self.session[settings.CART_SESSION_KEY] = self.cart
        self.session.modified = True

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

    def empty(self):
        for each in self.cart:
            del each
        self.save()



    def __iter__(self):
        product_ids = self.cart.keys()

        splitted = settings.PRODUCT_MODEL.split('.')
        app_label = splitted[0]
        model_name = splitted[1]

        try:
            model = apps.get_model(app_label, model_name)
        except LookupError:
            message = 'Model {} not found in app  {}'
            raise ModelDoesNotExist(message.format(model_name, app_label))

        products = model.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 __len__(self):
        return sum(item['quantity'] for item in self.cart.values())


    @property
    def total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

    @property
    def cart_length(self):
        return sum(item['quantity'] for item in self.cart.values())


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

1 个答案:

答案 0 :(得分:1)

问题是,当您创建购物车时,您创建一个空字典并将其分配给self.cart和会话:

cart = self.session[settings.CART_SESSION_KEY] = {}
self.cart = cart

但是当您清除购物车时,您创建一个空字典并仅将其分配给会话,让self.cart指向原始 - 仍然填充的字典:

self.session.cart[settings.CART_SESSION_KEY] = {}  # self.cart still populated

您可以清除原始词典,而不是在clear()中分配新词典:

def clear(self):
    self.cart.clear()  # Affects both self.cart and session
    self.session.modified = True