TypeError at /cart/add_cart/5/

I am trying to complete my first project. as I click on add to cart button the following exception comes: CartItem() got an unexpected keyword argument ‘quantity’

views.py

from django.shortcuts import redirect, render

from .models import Cart
from .models import CartItem, Product


# Create your views here.
def _cart_id(request):
    cart = request.session.session_key
    if not cart:
        cart = request.session.create()
    return cart

def add_cart(request, product_id): 
    product = Product.objects.get(id=product_id)  #get the product
    try:
        cart = Cart.objects.get(cart_id = _cart_id(request))  #get the cart using the cart_id present in the session
    except Cart.DoesNotExist:
        cart = Cart.objects.create(
            cart_id = _cart_id(request)
    )
    cart.save()

    try:
        cart_item = CartItem.objects.get(product=product, cart=cart)
        cart_item.QUANTITY += 1      
        cart_item.save()
    except CartItem.DoesNotExist:
        cart_item = CartItem.objects.create(
            product = product,
            quantity = 1,
            cart = cart,
        )
        cart_item.save()
    return redirect('cart')
 
def cart(request):
    return render(request, 'store/cart.html')

urls.py

from django.urls import path

from .import views

urlpatterns = [
    path('', views.cart, name='cart'),
    path('add_cart/<int:product_id>/', views.add_cart, name='add_cart'),

]

product_detail.html

{% if single_product.stock <= 0%}
        <h4 class= "text-danger">Out of Stock</h4>
        {% else %}
        <a href="{% url 'add_cart' single_product.id %}" class="btn  btn-primary"> <span class="text">Add to cart</span> <i class="fas fa-shopping-cart"></i></a>
        {% endif %}

please guide in this regard

Welcome @webextolcollege !

Side Note: When posting code, templates, error messages, or other preformatted / html text here, enclose the code between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code, then another line of ```. This forces the forum software to keep your code properly formatted. (I’ve taken the liberty of modifying your original post for this.)

Also, when requesting assistance for an error, please post the complete error with the traceback from the server console. (Posted as text as described above.)

Please post your CartItem model.

1 Like