1

I have a strange problem with creation of shopping cart I in Django 2.0. Sopping cart is and object inherited from request and stored in session:

class Cart(object):
    def __init__(self, request, shop_u_id):
        self.session_key = str(settings.CART_SESSION_ID)
        self.session = request.session
        cart = self.session.get(self.session_key)
        if not cart:
            cart = self.session[self.session_key] = {}
        self.cart = cart

I have no problem with set and get methods, but strange problem appeared in total sum function:

    def get_total_price(self):
        return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

I got an error:

Object of type 'Decimal' is not JSON serializable

But get_total_price nothing stores in session, it just for representation. (item['price'] stored as string)

enter image description here

Nick
  • 329
  • 3
  • 12
  • The Decimal class you are using is not JSON Serializable. Refer: https://stackoverflow.com/questions/1960516/python-json-serialize-a-decimal-object – Nihal Sharma Jul 03 '18 at 11:19
  • No one can answer your question without knowing exactly what you have in your session that is a Decimal - but YOU can get this information by inspecting the local vars (clicking on the little arrow next to the "Local vars" label in in the error page). – bruno desthuilliers Jul 03 '18 at 11:35
  • Also and FWIW: there's no reason this method would cause the problem since `json.dumps()` does not call methods. You either have a `Decimal` attribute or a `property` returning a `Decimal`, or the problem is completely unrelated to your cart. – bruno desthuilliers Jul 03 '18 at 11:54
  • It happens in POST request with redirect. Why Django try to serialize cart object created in view? – Nick Jul 03 '18 at 13:03

0 Answers0