我正在尝试在 Django 的视图之外设置一个变量会话。
我知道 django 关于 在视图之外使用会话 的文档。但就我而言,我尝试在自定义管理命令中设置会话变量。
这是我尝试过的:
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
我得到的是这个错误:
TypeError: 'Session' object does not support item assignment
如何将
my_variable
设置为 None
?
试试这个:
from django.contrib.sessions.models import Session
class Command(BaseCommand):
help = "My custom command."
def handle(self, *args, **options):
for session in Session.objects.all():
s = session.get_decoded()
s['my_variable'] = None
# so that any subsequent code which reads from the session sees your change
s.save()