【问题标题】:how to activate DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST如何激活 DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST
【发布时间】:2011-01-13 05:24:41
【问题描述】:

我读过这个

DJANGO.CORE.CONTEXT_PROCESSORS.REQUEST

如果TEMPLATE_CONTEXT_PROCESSORS 包含此处理器,则每个 RequestContext 将包含一个变量请求,即当前 Http请求。请注意,默认情况下不启用此处理器; 你必须激活它。

来自this page

但似乎没有关于如何激活此处理器的信息。

这是我最初的问题

Access request in django custom template tags

按照我的回答后

我还是有错误

TemplateSyntaxError at / Caught an exception while rendering: 'request' Original Traceback (most recent call last): 
File "C:\Python25\lib\site-packages\django\template\debug.py", line 71, in render_node result = node.render(context) 
File "C:\Python25\lib\site-packages\django\template__init__.py", line 936, in render dict = func(*args)
 File "c:\...\myapp_extras.py", line 7, in login request = context['request'] 
File "C:\Python25\lib\site-packages\django\template\context.py", line 44, in getitem raise KeyError(key) KeyError: 'request'

导致问题的代码是

request = context['request'] in

from django import template

register = template.Library()


@register.inclusion_tag('userinfo.html',takes_context = True)
def userinfo(context):
 request = context['request']
 address = request.session['address']
 return {'address':address}

【问题讨论】:

  • 看起来在 Google 网上帮助您的人很有帮助。您应该发布他要求的代码。

标签: django django-templates django-custom-tags


【解决方案1】:

我在这里回答了这个问题:How can I pass data to any template from any view in Django?

另请参阅我的答案中的 cmets...您可能也需要这些信息。

【讨论】:

  • 谢谢,但我已经通过了“takes_context = True”,并且我在 settings.py 中包含了“django.core.context_processors.request” 为什么当我调用 context['request'] 时它仍然会出现 KeyError
  • 为什么不打印上下文(或 context.keys()),看看里面有什么。显然,上下文没有“请求”键,所以看看它有什么键。
  • 抱歉再次询问..我得到了这个异常值:渲染时捕获异常:'Context'对象没有属性'keys'
  • 对不起...我以为 context 是一本字典,但它是一个 Context 对象。如果只打印上下文,它会输出什么?
  • 非常感谢 Andrew,原来我错过了在视图代码中传递“context_instance=RequestContext(request)”
【解决方案2】:

在 settings.py 中

from django.conf import global_settings

TEMPLATE_CONTEXT_PROCESSORS = global_settings.TEMPLATE_CONTEXT_PROCESSORS + (
    'django.core.context_processors.request',
)

【讨论】:

  • Note that a settings file should not import from global_settings, because that’s redundant --> docs.djangoproject.com/en/dev/topics/settings/#default-settings
  • 那条评论是关于导入一个变量只是为了重用它,无论如何都会发生这种情况。在这里,代码从 global_settings 添加到默认设置,因此需要导入它才能访问它。
猜你喜欢
  • 2019-07-13
  • 2012-01-27
  • 1970-01-01
  • 2019-11-02
  • 1970-01-01
  • 2023-03-08
  • 2019-07-05
  • 2021-07-18
  • 1970-01-01
相关资源
最近更新 更多