Я получил KeyError на /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу отладить его

Я получил KeyError в /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу его отладить cart.py

from decimal import Decimal
from django.conf import settings
from shopapp.models import Product

class Cart(object):
  def __init__(self, request):
#initialize the cart
    self.session=request.session
    cart=self.session.get(settings.CART_SESSION_ID)
    if not cart:
        #save an empty cart in the session
        cart=self.session[settings.CART_SESSION_ID]={}
    self.cart=cart

 #Access the related products in the cart through iteration
#i.e iterate over the items in the cart and get the products from the database
def __iter__(self):
    product_ids=self.cart.keys()
    #get the products objects and add them to the cart
    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 
        #adding a total price attribute

#counting all items in the cart
def __len__(self):
    return sum(item['quantity'] for item in self.cart.values())

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):
    #mark the session as modified to make sure it gets saved
    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()

#Calculate the total cost of items in the cart
def get_total_price(self):
    return sum(item['quantity'] * Decimal(item['price']) for item in self.cart.values())

#remove cart from the session
def clear(self):
    del self.session[settings.CART_SESSION_ID]
    self.save()

Я получил KeyError в /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу его отладить

views.py

from django.views.decorators.http import require_POST
from django.shortcuts import render, redirect, get_object_or_404
from shopapp.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')

Я получил KeyError в /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу его отладить

forms.py

from django import forms

PRODUCT_QUANTITY_CHOICES = [(i, str(i)) for i in range(1,21)]

class CartAddProductForm(forms.Form):
quantity=forms.TypedChoiceField(choices=PRODUCT_QUANTITY_CHOICES, coerce=int, label= 
('Quantity'))
override=forms.BooleanField(required=False,initial=False, widget=forms.HiddenInput)

Я получил KeyError в /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу его отладить

url.py

from django.urls import path
from .views import cart_add, cart_remove, cart_detail

app_name='cart'

urlpatterns=[
path('',cart_detail, name='cart_detail'),
path('add/<int:product_id>/',cart_add, name='cart_add'),
path('remove/<int:product_id>/', cart_remove, name='cart_remove'),
]

Я получил KeyError в /cart/add/3/ 'quantity' в моем приложении django shop и до сих пор не могу его отладить. Ошибка:

04/Aug/2022 16:27:28] "POST /cart/add/3/ HTTP/1.1" 500 74408
Internal Server Error: /cart/add/3/
Traceback (most recent call last):
File "C:\Users\Hp\anaconda3\envs\leon\lib\site- 
packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\Hp\anaconda3\envs\leon\lib\site-packages\django\core\handlers\base.py", 
line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Hp\anaconda3\envs\leon\lib\site- 
packages\django\views\decorators\http.py", line 40, in inner
return func(request, *args, **kwargs)
File "C:\Users\Hp\portfolio\ecommerce\shop\cart\views.py", line 15, in cart_add
cart.add(product=product,quantity=cd['quantity'],override_quantity=cd['override'])
File "C:\Users\Hp\portfolio\ecommerce\shop\cart\cart.py", line 43, in add
self.cart[product_id]['quantity'] += quantity
KeyError: 'quantity'
Вернуться на верх