Spaces:
Sleeping
Sleeping
| from django.shortcuts import render, redirect, get_object_or_404 | |
| from django.contrib.auth.decorators import login_required | |
| from django.utils.timezone import now | |
| from Boxes.models import MysteryBox | |
| from Accounts.models import Profile | |
| from .models import Cart, CartItem, Order, OrderItem, Payment | |
| def cart_detail(request): | |
| """Show all items in the cart""" | |
| profile = request.user.profile | |
| cart, created = Cart.objects.get_or_create(user=profile) | |
| return render(request, "templates/cart.html", {"cart": cart}) | |
| def cart_add(request, pk): | |
| """Add an item (MysteryBox) to the cart""" | |
| profile = request.user.profile | |
| cart, created = Cart.objects.get_or_create(user=profile) | |
| box = get_object_or_404(MysteryBox, pk=pk) | |
| item, created = CartItem.objects.get_or_create(cart=cart, box=box) | |
| item.quantity += 1 if not created else 1 | |
| item.save() | |
| return redirect("cart:cart_detail") | |
| def cart_remove(request, pk): | |
| """Remove one item from the cart""" | |
| profile = request.user.profile | |
| cart = get_object_or_404(Cart, user=profile) | |
| item = get_object_or_404(CartItem, cart=cart, pk=pk) | |
| item.delete() | |
| return redirect("cart:cart_detail") | |
| def checkout(request): | |
| """Convert cart into an order""" | |
| profile = request.user.profile | |
| cart = get_object_or_404(Cart, user=profile) | |
| if not cart.items.exists(): | |
| return redirect("cart:cart_detail") | |
| order = Order.objects.create( | |
| user=profile, | |
| total_amount=cart.total_amount | |
| ) | |
| for item in cart.items.all(): | |
| OrderItem.objects.create( | |
| order=order, | |
| box=item.box, | |
| quantity=item.quantity, | |
| unit_price=item.box.price | |
| ) | |
| cart.items.all().delete() | |
| return render(request, "templates/checkout_success.html", {"order": order}) | |