Ich verwende in meinem Projekt eine Klasse für den Warenkorb und überprüfe in init, ob 'cart' existiert in der Sitzung oder nicht, dann erstellen Sie einen Schlüssel für 'cart' wie folgt:
in der Klasse Cart:
Code: Select all
class Cart:
def __init__(self, request):
"""
Initialize The Cart
"""
self.request = request
self.session = request.session
cart = self.session.get('cart')
if not cart:
cart = self.session['cart'] = {}
self.cart = cart
# add a product to session cart:
def add(self, product, quantity=1):
"""
Add The Specified Product To The Cart If Exists
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': quantity}
else:
self.cart[product_id]['quantity'] += quantity
self.save()
Code: Select all
if 'cart' not in request.session:
self.cart = self.session['cart'] = {}
Formular für die Verwendung des Warenkorbs:
Code: Select all
class AddToCartProductForm(forms.Form):
QUANTITY_CHOICES = [(i, str(i)) for i in range(1, 30)]
quantity = forms.TypedChoiceField(choices=QUANTITY_CHOICES, coerce=int, label=_('Quantity'))
Code: Select all
def add_to_cart_view(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = AddToCartProductForm(request)
if form.is_valid():
cleaned_data = form.cleaned_data
quantity = cleaned_data['quantity']
cart.add(product, quantity)
return redirect('cart:cart-detail')
Code: Select all
urlpatterns = [
path('', views.cart_detail_view, name='cart-detail'),
path('add/', views.add_to_cart_view, name='add-to-cart')
]
Code: Select all
{% csrf_token %}
{{ add_to_cart_form|crispy }}
{% trans 'Add To Card' %}