Home > Software design >  Django: could not convert string to float: ''
Django: could not convert string to float: ''

Time:10-29

I am trying to write a function to display all items in cart, but it keeps showing this error could not convert string to float: " and i cannot tell where the problem is coming from? i have tried chaging the float(...) method to int(...). what the possible error?

def cart_view(request):
    cart_total_amount = 0
    if 'cart_data_obj' in request.session:
        for p_id, item in request.session['cart_data_obj'].items():
            print("Item PRice is ##################", item['price'])
            cart_total_amount  = int(item['qty']) * float(item['price'])

        return render(request, "core/cart.html", {'cart_data':request.session['cart_data_obj'], 'totalcartitems': len(request.session['cart_data_obj']), 'cart_total_amount':cart_total_amount})
    else:
        return render(request, 'core/cart.html', {'cart_data':'','totalcartitems':0,'cart_total_amount':cart_total_amount})

traceback

Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Item PRice is ################## 
Internal Server Error: /cart/
Traceback (most recent call last):
  File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Destiny\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Destiny\Desktop\E-commerce\ecomprj\core\views.py", line 230, in cart_view
    cart_total_amount  = int(item['qty']) * float(item['price'])
ValueError: could not convert string to float: ''
[28/Oct/2022 22:17:42] "GET /cart/ HTTP/1.1" 500 68398

CodePudding user response:

It looks like you are getting an empty string '' when trying to convert item['price'] into a float.

>>> float('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: ''

Make sure that item['price'] has a valid value before converting it to a float. From the error traceback you provided, it seems request.session['cart_data_obj'] is not having the right information. At some point where you set session['cart_data_obj'], the value for key "price" is being set to the empty string ''.

  • Related