You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
padelclub_backend/shop/cart.py

52 lines
1.8 KiB

from .models import CartItem, Product
def get_or_create_cart_id(request):
"""Get the cart ID from the session or create a new one"""
if 'cart_id' not in request.session:
request.session['cart_id'] = request.session.session_key or request.session.create()
return request.session['cart_id']
def get_cart_items(request):
"""Get all cart items for the current session"""
cart_id = get_or_create_cart_id(request)
return CartItem.objects.filter(session_id=cart_id)
def add_to_cart(request, product_id, quantity=1):
"""Add a product to the cart or update its quantity"""
product = Product.objects.get(id=product_id)
cart_id = get_or_create_cart_id(request)
try:
# Try to get existing cart item
cart_item = CartItem.objects.get(product=product, session_id=cart_id)
cart_item.quantity += quantity
cart_item.save()
except CartItem.DoesNotExist:
# Create new cart item
cart_item = CartItem.objects.create(
product=product,
quantity=quantity,
session_id=cart_id
)
return cart_item
def remove_from_cart(request, product_id):
"""Remove a product from the cart"""
cart_id = get_or_create_cart_id(request)
CartItem.objects.filter(product_id=product_id, session_id=cart_id).delete()
def update_cart_item(request, product_id, quantity):
"""Update the quantity of a cart item"""
cart_id = get_or_create_cart_id(request)
cart_item = CartItem.objects.get(product_id=product_id, session_id=cart_id)
if quantity > 0:
cart_item.quantity = quantity
cart_item.save()
else:
cart_item.delete()
def get_cart_total(request):
"""Calculate the total price of all items in the cart"""
return sum(item.product.price * item.quantity for item in get_cart_items(request))