The problem occurs when I try to add a product on cart just by clicking on add to cart button. the following bug occures. please cooperate with me in this regard thanks.
How can I modify my code so that as i click on add to cart button. concerned product will added in cart page
carts>views.py
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 file**
````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'),````
]