Создание сеанса корзины в Django
В корзину нельзя добавить более одного товара. После добавления товара его нельзя изменить в корзине.
from django.shortcuts import render, redirect, get_object_or_404
from django.views import View
from .cart_madule import Cart
from Product.models import Product
class CartDetailView(View):
def get(self, request):
cart = Cart(request)
return render(request, 'Cart/cart.html', {'cart': cart})
class CartAddView(View):
def post(self, request, pk):
product = get_object_or_404(Product, id=pk)
flavor, weight, quantity = request.POST.get('flavor'), request.POST.get('weight'), request.POST.get('quantity')
cart = Cart(request)
cart.add(product, flavor, weight, quantity)
return redirect('Cart:cart_detail')
Cart_Session_Id = 'cart'
class Cart:
def __init__(self, request):
self.session = request.session
cart = self.session.get(Cart_Session_Id)
if not cart:
cart = self.session[Cart_Session_Id] = {}
self.cart = cart
def __iter__(self):
cart = self.cart.copy()
for item in cart.values():
product = Product.objects.get(id=int(item['id']))
item['product'] = product
item['total'] = int(item['quantity']) * int(item['price'])
yield item
def unique_id_generator(self, id, flavor, weight):
result = f'{id}-{flavor}-{weight}'
return result
def add(self, product, quantity, flavor, weight):
unique = self.unique_id_generator(product.id, flavor, weight)
if unique not in self.cart:
self.cart[unique] = {'quantity': 0, 'price': str(product.Price), 'weight': weight, 'id': str(product.id),
'flavor': flavor}
else:
self.cart[unique]['quantity'] += int(quantity)
self.save()
def save(self):
self.session.modified = True