79 lines
2.2 KiB
Python
79 lines
2.2 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, get_or_create_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"))
|
|
cart, created = get_or_create_cart(request)
|
|
response = HttpResponse(status=201, headers={'HX-Trigger': 'updated-cart'})
|
|
|
|
if created and request.user.is_anonymous:
|
|
response.set_cookie(ANONYMOUS_CART_ID_COOKIE_NAME, cart.uuid)
|
|
|
|
# Comprobamos si existe una línea de carrito para ese carrito de ese producto
|
|
existing_cart_item = CartItem.objects.filter(cart=cart, product=product).first()
|
|
|
|
# Si existe, simplemente le sumamos la cantidad a la línea ya existente
|
|
if existing_cart_item is not None:
|
|
existing_cart_item.quantity += int(request.POST.get("quantity"))
|
|
existing_cart_item.save()
|
|
# Si no, lo creamos
|
|
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_or_create_cart(request)
|
|
cart_item = get_object_or_404(CartItem, pk=pk, cart=cart)
|
|
cart_item.delete()
|
|
return HttpResponse(status=204, headers={'HX-Trigger': 'updated-cart'})
|
|
|
|
|
|
index = IndexView.as_view()
|
|
product_detail = ProductDetail.as_view()
|