You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django ValueError:无法将空字符串转为浮点数问题求助

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: ''

问题背景

修改购物车价格选择器后,后端视图中item['price']为空字符串,导致浮点数转换失败。此前使用通用选择器.product-price时功能正常,控制台能输出正确价格500.00。

相关代码

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>&#x20BD <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);
            }
        });

问题原因

页面中存在两个带有.product-price-{{data.id}}类的元素:

  • 显示价格的<span>标签,价格值存储在文本内容中
  • 隐藏的<input>标签,价格值存储在value属性中

当JS使用$(".product-price-"+_index).text()时,会匹配到这两个元素。而<input>标签的文本内容为空(其值在value属性而非文本节点),导致最终获取到的_productPrice为空字符串,传递到后端后触发浮点数转换错误。

解决方法

方法1:精确选择隐藏input获取价格(推荐)

修改JS中的价格获取代码,明确选择隐藏的<input>标签并读取其value属性,该值直接来自后端,格式更可靠:

// 替换原价格获取代码
var _productPrice = $("input.product-price-"+_index).val();

方法2:区分显示与隐藏元素的类名

修改product.html中隐藏input的类名,避免与span的类重复:

<!-- 将隐藏input的类名修改为product-hidden-price-{{data.id}} -->
<input type="hidden" class="product-hidden-price-{{data.id}}" value="{{data.price}}" />

保持JS中获取显示span文本的代码不变:

var _productPrice = $(".product-price-"+_index).text();

方法3:后端添加容错处理

在视图函数中增加对空值的判断,避免程序崩溃:

def cart_list(request):
    total_amt = 0
    for p_id, item in request.session['cartdata'].items():
        # 处理空价格或无效值
        price = item.get('price', '0').strip()
        if not price:
            price = '0'
        total_amt += int(item['qty']) * float(price)
    return render(request, 'cart.html', {'cart_data': request.session['cartdata'], 'totalitems': len(request.session['cartdata']), 'total_amt': total_amt})

内容的提问来源于stack exchange,提问作者Artem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:20:39