ivbtar
ivbtar

Reputation: 879

Cannot store dictionary or object in request session in django view

I am trying to set a session in one view and read this session in another view. Trying to store a dictionary in session.

request.session['staffdict'] = staffdict

When i try to get dictionary from the session in second view :

staffdict = request.session.get('staffdict')

I get below error :

Django Version: 2.2.6 Exception Type: TypeError Exception Value:
Object of type 'UUID' is not JSON serializable Exception Location: /usr/lib/python3.6/json/encoder.py in default, line 180 Python Executable: /usr/local/bin/uwsgi Python Version: 3.6.8

Upvotes: 1

Views: 3111

Answers (3)

Vick A
Vick A

Reputation: 11

Django 3+, this seems to work for me...

request.session['cart'] = {}

Upvotes: 0

James Phillips
James Phillips

Reputation: 4647

I use pickle's dumps() and loads() functions, and convert the bytes objects from these methods to/from hex like so:

import pickle
dict = {'s':'string', 'i':1}
hexdict = pickle.dumps(dict).hex()

# the above hexdict should be JSON OK

dict2 = pickle.loads(bytes.fromhex(hexdict))
print(dict2)

Upvotes: 2

Grzegorz Bokota
Grzegorz Bokota

Reputation: 1804

You got response in error message. With your settings django serialize object to json and your dictionary contains non object which has no rule for serialize. documentation

I suggest to read also Write your own serializer. Then you can write something like this.

import uuid
import json

class SerializeUUIDEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, uuid.UUID):
            return {"__uuid__": True, "val": str(obj)}
        return super().default(o)


def serialize_hook(dkt: dict):
    if "__uuid__" in dkt:
        return uuid.UUID(dkt["val"])
    return dkt


class OwnSerilizer:
    def dumps(self, obj):
        return json.dumps(obj, cls=SerializeUUIDEncoder).encode('latin-1')

    def loads(self, data):
        return json.loads(data.decode('latin-1'), object_hook=serialize_hook)

this code use standard argument of json library methods. You can read more in dump documentation and in load documentation.

Upvotes: 1

Related Questions