I have a simple view
def foo(request):
card = Card.objects.latest(datetime)
request.session['card']=card
For the above code I get the error
"<Card: Card object> is not JSON serializable"
Django version 1.6.2. What am I doing wrong ?
There are two simple ways to do this. If each object belongs to a single session at the same time, store session id as a model field, and update models. If an object can belong to multiple sessions at the same time, store object.id as a session variable.
There are two simple ways to do this.
In a session, I'd just store the object primary key:
request.session['card'] = card.id
and when loading the card from the session, obtain the card again with:
try:
card = Card.objects.get(id=request.session['card'])
except (KeyError, Card.DoesNotExist):
card = None
which will set card
to None
if there isn't a card
entry in the session or the specific card doesn't exist.
By default, session data is serialised to JSON. You could also provide your own serializer, which knows how to store the card.id
value or some other representation and, on deserialization, produce your Card
instance again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With