I’m trying to set a variable to an expired session out of a view in Django.
I’m aware of django’s documentation on Using sessions out of views. But in my case, I try to set a session variable in a custom management command.
Here’s what I tried :
from django.contrib.sessions.models import Session
class Command(BaseCommand):
help = "My custom command."
def handle(self, *args, **options):
for s in Session.objects.all():
s['my_variable'] = None
What I get is this error:
TypeError: 'Session' object does not support item assignment
I also tried:
[…]
ss = SessionStore(session_key=s.session_key)
ss['my_variable'] = None
ss.save()
This creates another session but does not modify the existing one…
How can I set my_variable
to None
?
Edit: The session I’m trying to set a variable to is expired
You can’t do that on expired sessions. Django does not allow you.
But here is a hack:
class Command(BaseCommand):
help = "My custom command."
def handle(self, *args, **options):
future = datetime.datetime(datetime.MAXYEAR, 1, 1)
for s in Session.objects.all():
ed = s.expire_date
s.expire_date = future
s.save()
ss = SessionStore(session_key=s.session_key)
ss['my_variable'] = None
ss.save()
updated_session = Session.objects.get(session_key=s.session_key)
updated_session.expire_date = ed
updated_session.save()