我正在为我的愿望清单使用代码。我需要愿望清单中的产品在我的网站上显示。我尝试了各种方法,但我认为会议只会这样做。请一些帮助。
我该怎么做。
@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
答案 0 :(得分:2)
会话!= Cookies。会话由后端服务器管理,cookie发送给用户浏览器。 Django uses a single cookie to help track sessions但您只是在这种情况下使用Cookie。
会话框架允许您基于每个站点访问者存储和检索任意数据。它在服务器端存储数据并抽象cookie的发送和接收。 Cookie包含会话ID - 而不是数据本身(除非您使用基于cookie的后端)。
很难说出你想要的东西,但是如果你只是想要计算你在cookie中保存的项目数量,你只需要计算你的sku
并将它放在上下文中被发送到模板:
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 }}
模板中的