Я получаю MultiValueDictKeyError при нажатии на кнопку добавления в корзину
Я создал функцию add-to-cart для своего сайта, поэтому в моем product-detail.html:
{% for p in products %}
<div class="product-price">
<span id="current-product-price">Our Price:{{p.price}}</span>
<del>M.R.P: {{p.old_price}}</del>
</div>
<div class="button">
<input type="hidden" value="{{p.id}}" class="product-id" name="">
<input type="hidden" value="{{p.title}}" class="product-title" name="">
<a href="#" class="btn" id="add-to-cart-btn">Add to cart</a>
<a href="#" class="btn">Buy Now</a>
</div>
{% endfor %}
В моем файле function.js:
$("#add-to-cart-btn").on("click",function(){
let quantity=$("#product-quantity").val()
let product_title=$(".product-title").val()
let product_id=$(".product-id").val()
let product_price = $("#current-product-price").text()
let product_image = $(".product-image").val() //#1
let product_pid=$(".product-pid").val() //#2
let this_val=$(this)
console.log("Quantity:", quantity);
console.log("Id:", product_id);
console.log("PId:", product_pid);
console.log("Image:", product_image);
console.log("Title:", product_title);
console.log("Price:", product_price);
console.log("Current Element:", this_val);
$.ajax({
url: '/add-to-cart',
data: {
'id': product_id,
'pid': product_pid,
'image':product_image,
'qty': quantity,
'title': product_title,
'price': product_price
},
dataType: 'json',
beforeSend: function(){
console.log("Adding products to cart");
},
success: function(res){
this_val.html("Go to Cart")
console.log("Added products to cart");
$(".cart-items-count").text(response.totalcartitems)
}
})
})
В приведенной выше js-программе что-нибудь не так с ошибкой значения в product_pid(#2) & product_image(#1) и в my...... views.py:
def add_to_cart(request):
cart_product={}
cart_product[str(request.GET['id'])]={
'title': request.GET['title'],
'qty': request.GET['qty'],
'price': request.GET['price'],
'image': request.GET['image'], #1
'pid': request.GET['pid'], #2
}
if 'cart_data_obj' in request.session:
if str(request.GET['id']) in request.session['cart_data_obj']:
cart_data= request.session['cart_data_obj']
cart_data[str(request.GET['id'])]['qty']=int(cart_product[str(request.GET['id'])]['qty'])
cart_data.update(cart_data)
request.session['cart_data_obj']=cart_data
else:
cart_data=request.session['cart_data_obj']
cart_data.update(cart_product)
request.session['cart_data_obj']=cart_data
request.session['total_cart_items'] = len(cart_data)
else:
request.session['cart_data_obj']=cart_product
request.session['total_cart_items'] = len(cart_product)
return JsonResponse({"data":request.session['cart_data_obj'],'totalcartitems': request.session['total_cart_items']})
Я думаю, что ошибка возникает в файле views.py. Вы можете увидеть #1 & #2 в view.py
Когда я нажимаю на кнопку add-to-cart, я получаю ошибку значения error:
Internal Server Error: /add-to-cart/
Traceback (most recent call last):
File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__
list_ = super().__getitem__(key)
^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'image'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Sagarmoy Sadhukhan\Desktop\django ecom web\ecomprj\core\views.py", line 169, in add_to_cart
'image': request.GET['image'],
~~~~~~~~~~~^^^^^^^^^
File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'image'
[13/Mar/2024 08:42:06] "GET /add-to-cart/?id=7&qty=1&title=Apple&price=Our%20Price%3A1.99 HTTP/1.1" 500 75258