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

时间:2019-02-15 07:57:34

标签: python html django

我做了我的第一个购物车,一切正常,但是现在我想使当购物车为空时,他的链接应该写为“购物车为空”,但是当我向他放东西时,他的链接应该写为“购物车” ”。我在html中有该代码:

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

现在,当我在购物车页面中时,他的链接上写着“购物车”,但是当我在购物车页面外时,其链接上写着“购物车为空”,并且里面是否有任何产品都没有关系购物车与否。

cart.py

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())

1 个答案:

答案 0 :(得分: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变量。