[Answered ]-How to create an instance of an object in session using django?

2👍

Sessions in django are not stored in server memory, so they can’t contain pure objects. They are serialized to string that can be stored in some storage backend (database, cache, user cookies etc).

By default django uses JSON serializer for sessions. JSON Serializer can’t serialize objects.

There is another serializer built into django: pickle. It can serialize almost whatever you can create in python, but it has some drawbacks. It’s slower and when used together with any untrusted session storage (such as cookies), it can become very serious security breach, because it will allow attacker to run any code, just by swapping serialized data. See Django docs for more information.

Also, pickle on deserialization will just try to recreate object state from when it was serialized. This object won’t be just kept in memory, so consider if deserializing it from pickle is better than re-creating it from scratch (like you did it before).

Leave a comment