Files
shoppy/web/views.py
T
2024-11-27 17:07:03 +01:00

80 lines
2.0 KiB
Python

from django.shortcuts import get_object_or_404
from django.views.generic import TemplateView
from django.http.response import HttpResponse
from django.views.decorators.http import require_http_methods
from shop.models import Product, Cart, CartItem
from web.utils import get_cart
from web.settings import ANONYMOUS_CART_ID_COOKIE_NAME
class IndexView(TemplateView):
template_name = "web/index.html"
def get_context_data(self, **kwargs):
return {
"title": "Shoppy",
}
class ProductDetail(TemplateView):
template_name = "web/product_detail.html"
def get_context_data(self, pk, slug, **kwargs):
product = get_object_or_404(Product, pk=pk)
return {
"product": product,
"title": product.name,
"description": product.description,
"image": product.images.first(),
}
@require_http_methods(
[
"POST",
]
)
def add_cart_item(request, *args, **kwargs):
product = get_object_or_404(Product, pk=request.POST.get("product"))
response = HttpResponse(status=201)
if not request.user.is_authenticated:
cart = Cart.objects.create(
user=None,
)
else:
cart, created = Cart.objects.get_or_create(user=request.user)
response.set_cookie(ANONYMOUS_CART_ID_COOKIE_NAME, cart.uuid)
existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first()
if existing_cart_item is not None:
existing_cart_item.quantity += int(request.POST.get("quantity"))
existing_cart_item.save()
else:
CartItem.objects.create(
cart=cart,
quantity=request.POST.get("quantity"),
product=product,
)
return response
@require_http_methods(
[
"POST",
]
)
def delete_cart_item(request, pk, *args, **kwargs):
cart = get_cart(request)
cart_item = get_object_or_404(CartItem, pk=pk, cart=cart)
cart_item.delete()
return HttpResponse(status=204)
index = IndexView.as_view()
product_detail = ProductDetail.as_view()