我无法显示购物车商品。在之前的项目中,我使用了django 1.11并且该代码全部工作。但是现在我使用django 2.0并且我不知道我在某个地方犯了一个错误,或者它是django中的新东西。
购物车应用中的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, update_quantity=False):
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {"quantity": 0,
"price": str(product.price)}
if update_quantity:
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 __len__(self):
return sum(item["quantity"] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item["price"]) * item["quantity"] for item
in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.session.modified = True
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from shop.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd["quantity"],
update_quantity=cd["update"])
return redirect("cart:cart_detail")
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect("cart:cart_detail")
def cart_detail(request):
cart = Cart(request)
for item in cart:
item["update_quantity_form"] = CartAddProductForm(
initial={"quantity": item["quantity"],
"update": True})
return render(request, "cart/detail.html", {"cart": cart})
在模板中我尝试:
{% for item in cart %}
{% with product=item.products %}
<a href="{{ product.get_absolute_url }}">
<img src="{% if product.image %}{{ product.image.url}}
{% else %}{% static "img/no_image.png" %}{% endif %}">
</a>
{{ product.name }}
{% endwith %}
{% endfor %}
或:
{% for item in cart %}
<p>{{ item.product.name }}</p>
{% endfor %}
但我只看到明确的页面。
在终端中,我看到该项目已添加到购物车中:
[08/Feb/2018 11:34:14] "POST /cart/add/3/ HTTP/1.1" 302 0
但我无法在页面中显示购物车商品。我使用django 2.0和python 3.6
答案 0 :(得分:0)
这是我的错误,我在cart.py中丢失了一串代码。