【问题标题】:How to access session variable in child template in Django?如何在 Django 中访问子模板中的会话变量?
【发布时间】:2026-01-06 03:15:01
【问题描述】:

我正在尝试更改 Askbot 上的某些功能,使其根据会话显示不同版本的用户卡。我了解到我可以像从视图到模板的任何其他数据一样传递 request.session。但是,我要更改的模板隐藏在许多最终由视图呈现的父模板中。

我已经包含了上下文处理器(我正在使用 Django 1.8):

TEMPLATES = (
    {
        'BACKEND': 'askbot.skins.template_backends.AskbotSkinTemplates',
    },
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.core.context_processors.request',
                'django.contrib.auth.context_processors.auth',
            ]
        }
    },
)

在我看来:

def question(request, id, no_rep):
    if id == 1:
        request.session['no_rep'] = True
    else:
        request.session['no_rep'] = False
return render(request, 'question.html', data)

在我的模板中:

{% if request.session.no_rep == True %}

我仍然收到错误 'request' is undefined。 我错过了什么明显的东西吗?

这是完整的回溯:


Traceback:
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/views/readers.py" in question
  687.     return render(request, 'question.html', data)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/django/shortcuts.py" in render
  67.             template_name, context, request=request, using=using)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/django/template/loader.py" in render_to_string
  99.         return template.render(context, request)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/skins/template_backends.py" in render
  86.         return self.template.render(context)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/coffin/template/__init__.py" in render
  55.         return super(Template, self).render(**context)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/jinja2/environment.py" in render
  989.         return self.environment.handle_exception(exc_info, True)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/jinja2/environment.py" in handle_exception
  754.         reraise(exc_type, exc_value, tb)
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/question.html" in top-level template code
  388. {% from "macros.html" import comment_widget, tag_widget %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/two_column_body.html" in top-level template code
  1. {% extends "base.html" %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/base.html" in top-level template code
  45.             {% block body %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/two_column_body.html" in block "body"
  5.     {% block content%}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/question.html" in block "content"
  382.         {% include "question/content.html" %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/question/content.html" in top-level template code
  3. {% include "question/question_card.html" %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/question/question_card.html" in top-level template code
  31.                     {% include "question/question_author_info.html" %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/question/question_author_info.html" in top-level template code
  1. {{ macros.post_last_updater_and_creator_info(question) }}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/macros.html" in template
  108.         {{ post_contributor_info(first_rev, "original_author") }}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/macros.html" in template
  216.         {{ post_contributor_avatar_and_credentials(revision) }}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/macros.html" in template
  64.         {{ user_card(revision.author) }}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/macros.html" in template
  649.     {% include "widgets/user_card.html" %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-devel/askbot/templates/widgets/user_card.html" in top-level template code
  13.         {% if request.session.no_rep == True %}
File "/mnt/c/Users/Lea Quan/Desktop/LITWC/askbot-venv/local/lib/python2.7/site-packages/jinja2/environment.py" in getattr
  408.             return getattr(obj, attribute)

Exception Type: UndefinedError at /question/1/how-to-deselect-word-in-thinking-vs-clicking-in-modern-user-interfaces/
Exception Value: 'request' is undefined

【问题讨论】:

  • 在使用上下文变量方面,基本模板和子模板没有区别。如果您可以访问request 上下文变量(即在您的settings.py 中有django.core.context_processors.request),您可以使用{{ request.session.my_var }} 简单地访问任何会话变量。详细解释见this question
  • 我想我对这些上下文的范围感到困惑。如果我有return render(request, 'question.html', data) 在我看来。 request.session 是否只能在 question,html 中访问?我正在尝试从包含在question.html 深处的模板访问request.session。目前我收到一个例外,说'request' is undefined
  • 您是否手动将request 包含在您的data 字典中?如果您这样做,它将仅对该视图可用。这就是为什么您需要在您的CONTEXT_PROCESSORS 设置中包含django.core.context_processors.request。上下文处理器向所有视图注入额外的上下文变量,这样您就不必重复自己。
  • 嗨,我不包括手动请求,我认为我的处理器设置正确。但是,我仍然收到错误消息,并且我在上面包含了我的代码。
  • 删除 django.core.context_processors.request 并仅保留 django.template.context_processors.request。请发布带有完整回溯的错误消息。

标签: html django templates session view


【解决方案1】:

我发现了问题所在。我试图从中访问变量的视图以调用但不包含的方式与模板断开连接。我必须将请求变量传递给该视图。

【讨论】: