From 17ecadf69561fe6f39b1247f12b28e96d5c6adca Mon Sep 17 00:00:00 2001 From: divanov11 <33843378+divanov11@users.noreply.github.com> Date: Wed, 22 Apr 2020 19:32:47 -0700 Subject: [PATCH] Create m3-p1-s8-views.py --- m3-p1-s8-views.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 m3-p1-s8-views.py diff --git a/m3-p1-s8-views.py b/m3-p1-s8-views.py new file mode 100644 index 0000000..11682c6 --- /dev/null +++ b/m3-p1-s8-views.py @@ -0,0 +1,78 @@ +from django.shortcuts import render +from django.http import JsonResponse +import json + +from .models import * + +def store(request): + + if request.user.is_authenticated: + customer = request.user.customer + order, created = Order.objects.get_or_create(customer=customer, complete=False) + items = order.orderitem_set.all() + cartItems = order.get_cart_items + else: + #Create empty cart for now for non-logged in user + items = [] + order = {'get_cart_total':0, 'get_cart_items':0} + cartItems = order['get_cart_items'] + + products = Product.objects.all() + context = {'products':products, 'cartItems':cartItems} + return render(request, 'store/store.html', context) + +def cart(request): + + if request.user.is_authenticated: + customer = request.user.customer + order, created = Order.objects.get_or_create(customer=customer, complete=False) + items = order.orderitem_set.all() + cartItems = order.get_cart_items + else: + #Create empty cart for now for non-logged in user + items = [] + order = {'get_cart_total':0, 'get_cart_items':0} + cartItems = order['get_cart_items'] + + context = {'items':items, 'order':order, 'cartItems':cartItems} + return render(request, 'store/cart.html', context) + +def checkout(request): + if request.user.is_authenticated: + customer = request.user.customer + order, created = Order.objects.get_or_create(customer=customer, complete=False) + items = order.orderitem_set.all() + cartItems = order.get_cart_items + else: + #Create empty cart for now for non-logged in user + items = [] + order = {'get_cart_total':0, 'get_cart_items':0} + cartItems = order['get_cart_items'] + + context = {'items':items, 'order':order, 'cartItems':cartItems} + return render(request, 'store/checkout.html', context) + +def updateItem(request): + data = json.loads(request.body) + productId = data['productId'] + action = data['action'] + print('Action:', action) + print('Product:', productId) + + customer = request.user.customer + product = Product.objects.get(id=productId) + order, created = Order.objects.get_or_create(customer=customer, complete=False) + + orderItem, created = OrderItem.objects.get_or_create(order=order, product=product) + + if action == 'add': + orderItem.quantity = (orderItem.quantity + 1) + elif action == 'remove': + orderItem.quantity = (orderItem.quantity - 1) + + orderItem.save() + + if orderItem.quantity <= 0: + orderItem.delete() + + return JsonResponse('Item was added', safe=False)