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.
46 lines
1.5 KiB
46 lines
1.5 KiB
from django.shortcuts import render, redirect, get_object_or_404
|
|
from django.contrib import messages
|
|
from .models import Product, CartItem
|
|
from . import cart
|
|
|
|
# Create your views here.
|
|
def product_list(request):
|
|
products = Product.objects.all()
|
|
cart_items = cart.get_cart_items(request)
|
|
total = cart.get_cart_total(request)
|
|
return render(request, 'shop/product_list.html', {
|
|
'products': products,
|
|
'cart_items': cart_items,
|
|
'total': total
|
|
})
|
|
|
|
def view_cart(request):
|
|
"""Display the shopping cart"""
|
|
cart_items = cart.get_cart_items(request)
|
|
total = cart.get_cart_total(request)
|
|
return render(request, 'shop/cart.html', {
|
|
'cart_items': cart_items,
|
|
'total': total
|
|
})
|
|
|
|
def add_to_cart_view(request, product_id):
|
|
"""Add a product to the cart"""
|
|
product = get_object_or_404(Product, id=product_id)
|
|
quantity = int(request.POST.get('quantity', 1))
|
|
|
|
cart.add_to_cart(request, product_id, quantity)
|
|
messages.success(request, f'{product.title} added to your cart')
|
|
|
|
return redirect('shop:product_list')
|
|
|
|
def update_cart_view(request, product_id):
|
|
"""Update cart item quantity"""
|
|
if request.method == 'POST':
|
|
quantity = int(request.POST.get('quantity', 0))
|
|
cart.update_cart_item(request, product_id, quantity)
|
|
return redirect('shop:view_cart')
|
|
|
|
def remove_from_cart_view(request, product_id):
|
|
"""Remove item from cart"""
|
|
cart.remove_from_cart(request, product_id)
|
|
return redirect('shop:view_cart')
|
|
|