在我的购物网站应用中显示购物车状态

问题描述 投票:0回答:1

我制作了我的第一个购物车,一切正常,但现在我想要当购物车是空的,然后他的链接应该写“购物车是空的”,但是当我将东西给他时,他的链接应该写成“购物车”。我在html中有这个代码:

<a href="http://127.0.0.1:8000/cart/">
    {% if cart == None %}cart is empty{% else %}cart{% endif %}
</a>

现在,当我在购物车页面,然后他的链接写了“购物车”,但当我在购物车页面外,然后它的书面“购物车是空的”,如果购物车中有一些产品没有问题。

cart.朋友

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

class Cart(object):

def __init__(self, request):
    self.session=request.session
    cart=self.session.get(settings.CART_SESSION_ID)
    if not cart:
        cart = self.session[settings.CART_SESSION_ID] = {}
    self.cart=cart

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

    self.save()

def save(self):
    self.session[settings.CART_SESSION_ID] = 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 __iter__(self):
    product_ids=self.cart.keys()
    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 clear(self):
    del self.session[settings.CART_SESSION_ID]

def get_total_price(self):
    return sum(Decimal(item['price'])*item['quantity'] for item in   self.cart.values())
python html django
1个回答
1
投票

要扩展我的评论,您需要在应用的每个页面中插入cart对象,而不仅仅是/cart/页面。你可以用"context processor"做到这一点:

在你的context_processors.py应用程序中创建一个cart并添加如下内容:

from cart import Cart

def cart_processor(request):
    return {
        # You need to be sure that this is returning the cart
        # that is unique for the current user. It looks like you
        # are doing this already in the __init__ method, but just
        # be sure that you don't accidently insert the wrong object
        'cart': Cart(request)
    }

然后在您的设置中,找到TEMPLATES.context_processors设置并添加新上下文处理器的路径:

TEMPLATES = [
     ...
     OPTIONS = {
         ...
         "context_processors": [
             ...
             "cart.context_processors.cart_processor",
             ...

您现在可以在应用中的每个模板中使用cart变量。

© www.soinside.com 2019 - 2024. All rights reserved.