chore: splitted views file into separated files
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
from django.http.response import HttpResponse
|
||||
from django.shortcuts import get_object_or_404
|
||||
from django.views.decorators.http import require_http_methods
|
||||
from django.views.generic import TemplateView, View
|
||||
|
||||
from shop.models import CartItem, Product
|
||||
from web.settings import ANONYMOUS_CART_ID_COOKIE_NAME
|
||||
from web.utils import get_or_create_cart
|
||||
|
||||
|
||||
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, created = 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()
|
||||
Reference in New Issue
Block a user