0

我正在为我的愿望清单使用代码。我需要愿望清单中的产品数量才能在我的网站上显示。我尝试了各种方法,但我认为会话只会这样做。请帮忙。

我怎么能这样做。

@never_cache
def wishlist(request, template="shop/wishlist.html"):
    """
    Display the wishlist and handle removing items from the wishlist and
    adding them to the cart.
    """

    skus = request.wishlist
    error = None
    if request.method == "POST":
        to_cart = request.POST.get("add_cart")
        add_product_form = AddProductForm(request.POST or None,
                                          to_cart=to_cart,request=request)
        if to_cart:
            if add_product_form.is_valid():
                request.cart.add_item(add_product_form.variation, 1,request)
                recalculate_discount(request)
                message = _("Item added to cart")
                url = "shop_cart"
            else:
                error = add_product_form.errors.values()[0]
        else:
            message = _("Item removed from wishlist")
            url = "shop_wishlist"
        sku = request.POST.get("sku")
        if sku in skus:
            skus.remove(sku)
        if not error:
            info(request, message)
            response = redirect(url)
            set_cookie(response, "wishlist", ",".join(skus))
            return response

    # Remove skus from the cookie that no longer exist.
    published_products = Product.objects.published(for_user=request.user)
    f = {"product__in": published_products, "sku__in": skus}
    wishlist = ProductVariation.objects.filter(**f).select_related(depth=1)
    wishlist = sorted(wishlist, key=lambda v: skus.index(v.sku))
    context = {"wishlist_items": wishlist, "error": error}
    response = render(request, template, context)
    if len(wishlist) < len(skus):
        skus = [variation.sku for variation in wishlist]
        set_cookie(response, "wishlist", ",".join(skus))
    return response
4

1 回答 1

2

会话!= Cookie。会话由后端的服务器管理,cookie 被发送到用户浏览器。Django 使用单个 cookie 来帮助跟踪会话,但在此实例中您只是使用 cookie。

会话框架允许您基于每个站点访问者存储和检索任意数据。它将数据存储在服务器端,并抽象了 cookie 的发送和接收。Cookie 包含会话 ID——而不是数据本身(除非您使用基于 cookie 的后端)。

很难说出您想要什么,但如果您只是想计算保存在 cookie 中的项目数,您只需计算您sku的 s 并将其放入发送到模板的上下文中:

if len(wishlist) < len(skus):
    skus = [variation.sku for variation in wishlist]
    set_cookie(response, "wishlist", ",".join(skus))
context = {"wishlist_items": wishlist, "error": error, "wishlist_length":len(wishlist)}
return render(request, template, context)

并使用:

{{ wishlist_length }}

在您的模板中

于 2013-06-21T10:50:48.427 回答