Request.session['some_variable'] TypeError: Object of type Decimal is not JSON serializable

I´m updating some code from Django 1.8 and python 2.7 to django 5.0 and python 3.11, in the old version in some functions are make session variables that store decimal values and after that make a redirect like this:

request.sessions['decimal_var'] = 1.00
return HttpResponseRedirect('/somepage/')

This works fine in the old version so the 'decimal_var' can be used in the redirected page, but in the new version (Django 5.0) if I pass any session variable with decimal value gives me this error:

  File "C:\Python311\Lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
          ^^^^^^^^^^^
  File "C:\Python311\Lib\json\encoder.py", line 200, in encode
    chunks = self.iterencode(o, _one_shot=True)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\encoder.py", line 258, in iterencode
    return _iterencode(o, 0)
           ^^^^^^^^^^^^^^^^^
  File "C:\Python311\Lib\json\encoder.py", line 180, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

One option is just pass int or string values, but i think this is not a real solution and why the new versions can´t manage the decimal values and the old can, this could bring more problems if is a need to use decimal values. Is there a way to manage the decimal values in the session variables?

Back to Top