Как работает django add to cart с ajax-jquery?
` моя переменная productid из ajax данных ниже возвращает пустую строку но моя цель - вернуть id товара из сессий django, когда пользователь нажимает на кнопку add-to-cart ,
<script>
$(document).on('click', '#add-cart-btn', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'storebasket:add_to_cart'%}",
data:{
productid: $("#add-cart-btn").val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post"
},
success: function(json){
},
error: function (xhr, errmsg, err) {}
});
})
</script>`
` Здесь показана ошибка:
`
` Файл "C:\Users\DELL\Documents\PROGRAMMING\VSCODE\PYTHON\ecommerce\storebasket\views.py", строка 19, in add_to_cart
product_id = int(request.POST.get('productid')) ValueError: недопустимый литерал для int() с основанием 10: '' `
The view that raises the error:
# capture ajax data
def add_to_cart(request):
basket =MySession(request)
if request.POST.get('action') == 'post':
product_id = int(request.POST.get('productid'))
product=get_object_or_404(Product, id=product_id)
# save to MySession
basket.add(product=product)
response=JsonResponse({'test': 'data'})
return response
My session creation code is as follows:
class MySession():
def __init__(self,request):
self.session=request.session
basket=self.session.get('S_key')
if 'S_key' not in request.session:
basket=self.session['S_key']={}
self.basket=basket
#request.session.modified = True
def add(self, product):
"""
Adding and updating the users basket session data
"""
product_id = product.id
if product_id not in self.basket:
self.basket[product_id] = {'price': str(product.price)}
# save in the session
self.session.modified = True