This is views.py file from the cart section where I want to add product, remove product and show product details in the cart. Error is : Cart() takes no arguments.
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from ecommerce.models import Product
from .cart import Cart
from .forms import CartAddProductForm
@require_POST
def cart_add(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
form = CartAddProductForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
cart.add(product=product,
quantity=cd['quantity'],
override_quantity=cd['override'])
return redirect('cart:cart_detail')
@require_POST
def cart_remove(request, product_id):
cart = Cart(request)
product = get_object_or_404(Product, id=product_id)
cart.remove(product)
return redirect('cart:cart_detail')
def cart_detail(request):
cart = Cart(request)
products = []
for item in cart:
item['update_quantity_form'] = CartAddProductForm(initial={
'quantity': item['quantity'],
'override': True})
return render(request, 'cart/detail.html', {'cart': cart})
This is my cart.py file where shopping cart can be managed. Here is the method to add, remove, iteration over the items in the cart etc.
from decimal import Decimal
from django.conf import settings
from ecommerce.models import Product
class Cart:
def __int__(self, request):
"""
Initialize the cart.
"""
self.session = request.session
cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
def add(self, product, quantity=1, override_quantity=False):
"""
Add a product to the cart or update its quantity
"""
product_id = str(product.id)
if product_id not in self.cart:
self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
if override_quantity:
self.cart[product_id]['quantity'] = quantity
else:
self.cart[product_id]['quantity'] = quantity
self.save()
def save(self):
self.session.modified = True
def remove(self, product):
"""
Remove a product from the cart.
"""
product_id = str(product.id)
if product_id in self.cart:
del self.cart[product_id]
self.save()
def __iter__(self):
"""
Iterate over the items in the cart and het the products
from the database
"""
product_ids = self.cart.keys()
products = Product.objects.filter(id_in=product_ids)
cart = self.cart.copy()
for product in products:
cart[str(product.id)]['product'] = product
for item in cart.values():
item['price'] = Decimal(item['price'])
item['total_price'] = item['price'] * item['quantity']
yield item
def __len__(self):
"""
Count all the items in the cart
"""
return sum(item['quantity'] for item in self.cart.values())
def get_total_price(self):
return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())
def clear(self):
del self.session[settings.CART_SESSION_ID]
self.save()
Traceback Error:
Traceback (most recent call last):
File "C:\Users\bbkra\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
response = get_response(request)
File "C:\Users\bbkra\PycharmProjects\djangoProject\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\bbkra\PycharmProjects\djangoProject\venv\lib\site-packages\django\views\decorators\http.py", line 43, in inner
return func(request, *args, **kwargs)
File "C:\Users\bbkra\PycharmProjects\djangoProject\cart\views.py", line 10, in cart_add
cart = Cart(request)
TypeError: Cart() takes no arguments
CodePudding user response:
I could see one mistake it should be __init__()
method not __int__
method.
That's why Cart(request)
gave that error as __init__()
was not actually called.