feat: cart
This commit is contained in:
+49
-20
@@ -1,9 +1,11 @@
|
||||
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.filters import ProductFilter
|
||||
from shop.models import Product
|
||||
from web.mixins import FilteredQuerysetMixin, PaginatedQuerysetMixin
|
||||
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):
|
||||
@@ -15,22 +17,6 @@ class IndexView(TemplateView):
|
||||
}
|
||||
|
||||
|
||||
class ListProducts(TemplateView, FilteredQuerysetMixin, PaginatedQuerysetMixin):
|
||||
template_name = "web/list_products.html"
|
||||
queryset = Product.objects.all()
|
||||
filter_class = ProductFilter
|
||||
|
||||
def get_context_data(self, **kwargs):
|
||||
qs = self.get_queryset()
|
||||
page = self.get_paginated_queryset(qs)
|
||||
|
||||
return {
|
||||
"page": page,
|
||||
"has_next_page": page.has_next(),
|
||||
"has_previous_page": page.has_previous(),
|
||||
}
|
||||
|
||||
|
||||
class ProductDetail(TemplateView):
|
||||
template_name = "web/product_detail.html"
|
||||
|
||||
@@ -45,6 +31,49 @@ class ProductDetail(TemplateView):
|
||||
}
|
||||
|
||||
|
||||
@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()
|
||||
list_products = ListProducts.as_view()
|
||||
product_detail = ProductDetail.as_view()
|
||||
|
||||
Reference in New Issue
Block a user