学习Django与教程和有错误.
File "F:\Python\COTSW\teashop\main\views.py", line 98, in cart_list total_amt+=int(item['qty'])*float(item['price'])
个
ValueError: could not convert string to float: ''
个
Views.py
def cart_list(request):
total_amt = 0
for p_id, item in request.session['cartdata'].items():
total_amt+=int(item['qty'])*float(item['price'])
return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt})
Product.html
<div class="col-md-8">
<p>{{data.detail}}</p>
<hr/>
<table class="table table-bordered">
<tr>
<h6>Цена</h6>
<h6>₽ <span class="product-price-{{data.id}}">{{data.price}}</span></h6>
</tr>
</table>
<hr/>
<div class="input-group my-3" style="width:30%;">
<input type="number" value="1" class="form-control product-qty-{{data.id}}" id="productQty" />
<div class="input-group-append">
<input type="hidden" class="product-id-{{data.id}}" value="{{data.id}}" />
<input type="hidden" class="product-title-{{data.id}}" value="{{data.title}}" />
<input type="hidden" class="product-image-{{data.id}}" value="{{data.image}}" />
<input type="hidden" class="product-price-{{data.id}}" value="{{data.price}}" />
<button class="btn btn-primary btn-sm add-to-cart" data-index="{{data.id}}" type="button" id="addToCartBtn"><i class="fa fa-shopping-cart"></i> В корзину</button>
</div>
</div>
</div>
Custom.js
$(document).on('click', ".add-to-cart", function(){
var _vm=$(this);
var _index=_vm.attr('data-index');
var _qty = $(".product-qty-"+_index).val();
var _productId = $(".product-id-"+_index).val();
var _productTitle = $(".product-title-"+_index).val();
var _productImage = $(".product-image-"+_index).val();
var _productPrice = $(".product-price-"+_index).text();
var _productSlug = $(".product-slug-"+_index).val();
console.log(_productPrice)
// Ajax
$.ajax({
url:'/add-to-cart',
data:{
'qty':_qty,
'id':_productId,
'title':_productTitle,
'image':_productImage,
'price':_productPrice,
'slug':_productSlug,
},
dataType:'json',
beforeSend:function(){
_vm.attr('disabled', true);
},
success:function(res){
$(".cart-list").text(res.totalitems);
_vm.attr('disabled',false);
}
});
在更改之前,var _productPrice = $(".product-price").text();
是var _productPrice = $(".product-price").text();
,并且工作正常.日志(log)显示正确的价格为500.00,但采用空字符串.
教程中的所有内容都运行正常,我不明白哪里会出错.