Django: could not convert string to float: ''

Question:

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:UsersDestinyAppDataLocalProgramsPythonPython39libsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:UsersDestinyAppDataLocalProgramsPythonPython39libsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:UsersDestinyDesktopE-commerceecomprjcoreviews.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
Asked By: Destiny Franks

||

Answers:

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

Answered By: lmiguelvargasf
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.