daily pastebin goal
83%
SHARE
TWEET

Untitled

a guest Dec 18th, 2018 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Cart(object):
  2.     def __init__(self, request):
  3.         self.session = request.session
  4.         cart = self.session.get(settings.CART_SESSION_ID)
  5.         if not cart:
  6.             cart = self.session[settings.CART_SESSION_ID] = {}
  7.         self.cart = cart
  8.  
  9.     def add(self, product, quantity=1, update_quantity=False):
  10.         product_id = str(product.id)
  11.         if product_id not in self.cart:
  12.             self.cart[product_id] = {'quantity': 0,
  13.                                      'price': str(product.price)}
  14.         if update_quantity:
  15.             self.cart[product_id]['quantity'] = quantity
  16.         else:
  17.             self.cart[product_id]['quantity'] += quantity
  18.         self.save()
  19.  
  20.     def save(self):
  21.         self.session[settings.CART_SESSION_ID] = self.cart
  22.         self.session.modified = True
  23.  
  24.     def remove(self, product):
  25.         product_id = str(product.id)
  26.         if product_id in self.cart:
  27.             del self.cart[product_id]
  28.             self.save()
  29.  
  30.     def __iter__(self):
  31.         product_ids = self.cart.keys()
  32.         products = Product.objects.filter(id__in=product_ids)
  33.         for product in products:
  34.             self.cart[str(product.id)]['product'] = product
  35.  
  36.         for item in self.cart.values():
  37.             item['price'] = Decimal(item['price'])
  38.             item['total_price'] = item['price'] * item['quantity']
  39.             yield item
  40.  
  41.     def __len__(self):
  42.         return sum(item['quantity'] for item in self.cart.values())
  43.  
  44.     def get_total_price(self):
  45.         return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
  46.  
  47.     def clear(self):
  48.         del self.session[settings.CART_SESSION_ID]
  49.         self.session.modified = True
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top