在视图 django 之外使用会话

use sessions out of the views django

我在我的 Django 应用程序中使用 this 文档制作了一个自定义模板标签:

myproject/
    __init__.py
    models.py
    templatetags/
        __init__.py
        myCustomTags.py
    views.py

myCustomTags.py 中,我需要使用 views.py
中的一些变量 所以我将这些变量保存在 session 中,并试图将它们放入 myCustomTags.py,但注意工作并且它不识别我的会话。
我使用了 this doc ,但似乎这种方法要我使用 session_keys。在这种方法中,我的问题 是如何在没有密钥的情况下使用会话或以某种方式将密钥从 views.py 传递到 myCustomTags.py

这是我在这个方法中的代码:

views.py:

from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
from django.contrib.sessions.backends.db import SessionStore
my_session = SessionStore()

def user_login(request):
    if request.method == "POST":
        username = request.POST.get('username')
        password = request.POST.get('password')
        # some process to validate and etc...
        my_session['test_session'] = 'this_is_my_test'
        my_session.create()
        return redirect(reverse('basic_app:index'))

myCustomTags.py

from django import template
from importlib import import_module
from django.conf import settings
SessionStore = import_module(settings.SESSION_ENGINE).SessionStore
from django.contrib.sessions.backends.db import SessionStore

my_session = SessionStore()
register = template.Library()

@register.simple_tag
def userStatusMode():
    status = my_session['test_session']
    return status

base.html:

{% load dynamic_vars %}
{% userStatusMode as user_status_thing %}
 <!-- and somewher in base.html -->
{{user_status_thing}}

另一种方法是在 views.py 中使用 requst.sessions 并尝试在 myCustomTags.py 中使用它们,但这也没有用。

顺便问一下,如何在视图之外使用会话? 我在这里遗漏了什么吗?

这是各种错误。

您不应该直接实例化 SessionStore。按照您的操作方式,您没有给出任何指示 您正在尝试获取或设置哪个 用户会话。

相反,您应该通过 request.session.

访问当前用户的会话
request.session['test_session'] = 'this_is_my_test'

同样在模板中,你可以直接访问会话字典(不需要模板标签):

{{ request.session.test_session }}