使用视图之外的会话django

时间:2019-02-25 18:07:12

标签: python django python-3.x django-sessions

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

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

myCustomTags.py中,我需要使用views.py
中的一些变量。 因此我将这些变量保存在session中,并尝试在myCustomTags.py中获取它们,但是注意到它起作用并且无法识别我的会话。
我使用了this文档,但似乎此方法希望我使用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中。

顺便说一句,如何在视图之外使用会话? 我在这里想念什么吗?

1 个答案:

答案 0 :(得分:1)

这是各种各样的错误。

您不应该直接实例化SessionStore。完成此操作的方式并未表示您要尝试获取或设置哪个 用户会话。

相反,您应该通过request.session访问当前用户的会话。

request.session['test_session'] = 'this_is_my_test'

,并且在模板中类似,您可以在其中直接访问会话字典(无需模板标签):

{{ request.session.test_session }}
相关问题