first commit
This commit is contained in:
66
cart/views.py
Normal file
66
cart/views.py
Normal file
@@ -0,0 +1,66 @@
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.response import Response
|
||||
from rest_framework import status
|
||||
from django.shortcuts import get_object_or_404
|
||||
from product.models import Product
|
||||
from .cart import Cart
|
||||
from .serializers import CartSerializer, CartAddProductSerializer
|
||||
|
||||
class CartDetailView(APIView):
|
||||
def get(self, request):
|
||||
cart = Cart(request)
|
||||
# Cart.__iter__ zaten dict döndürüyor, direkt listeye çevirebiliriz.
|
||||
cart_items = list(cart)
|
||||
|
||||
data = {
|
||||
'items': cart_items,
|
||||
'total_price': cart.get_total_price()
|
||||
}
|
||||
|
||||
serializer = CartSerializer(data)
|
||||
return Response(serializer.data)
|
||||
|
||||
class CartAddView(APIView):
|
||||
def post(self, request):
|
||||
serializer = CartAddProductSerializer(data=request.data)
|
||||
if serializer.is_valid():
|
||||
product_id = serializer.validated_data['product_id']
|
||||
quantity = serializer.validated_data['quantity']
|
||||
override_quantity = serializer.validated_data['override_quantity']
|
||||
|
||||
product = get_object_or_404(Product, id=product_id)
|
||||
cart = Cart(request)
|
||||
cart.add(product=product, quantity=quantity, override_quantity=override_quantity)
|
||||
|
||||
# Güncel sepeti döndür
|
||||
cart_items = list(cart)
|
||||
|
||||
data = {
|
||||
'items': cart_items,
|
||||
'total_price': cart.get_total_price()
|
||||
}
|
||||
|
||||
return Response(CartSerializer(data).data, status=status.HTTP_200_OK)
|
||||
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
class CartRemoveView(APIView):
|
||||
def delete(self, request, product_id):
|
||||
product = get_object_or_404(Product, id=product_id)
|
||||
cart = Cart(request)
|
||||
cart.remove(product)
|
||||
|
||||
# Güncel sepeti döndür
|
||||
cart_items = list(cart)
|
||||
|
||||
data = {
|
||||
'items': cart_items,
|
||||
'total_price': cart.get_total_price()
|
||||
}
|
||||
|
||||
return Response(CartSerializer(data).data, status=status.HTTP_200_OK)
|
||||
|
||||
class CartClearView(APIView):
|
||||
def post(self, request):
|
||||
cart = Cart(request)
|
||||
cart.clear()
|
||||
return Response({'message': 'Cart cleared'}, status=status.HTTP_200_OK)
|
||||
Reference in New Issue
Block a user