我在我的Django应用程序中使用this doc制作了一个自定义模板标签:
myproject/
__init__.py
models.py
templatetags/
__init__.py
myCustomTags.py
views.py
在myCustomTags.py
中,我需要使用views.py中的一些变量
所以我在会话中保存这些变量,并尝试在myCustomTags.py
中获取它们,但注意到有效并且它无法识别我的会话。
我使用了this doc,但似乎这个方法要我使用session_keys。在这个方法中,我的问题是如何使用没有键的会话或以某种方式将关键字从views.py传递给myCustomTags.py
。
这是我在这个方法中的代码:
views.朋友:
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'))
没有custom tags.朋友
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'
类似地,在模板中,您可以直接访问会话dict(不需要模板标记):
{{ request.session.test_session }}