gpt4 book ai didi

django 自定义模板标签未在上下文中收到请求

转载 作者:行者123 更新时间:2023-12-01 08:16:00 25 4
gpt4 key购买 nike

我正在使用 django 1.4 并尝试转换 this article 末尾描述的代码进入自定义标签。这意味着我需要访问请求中的 is_secure 和 site_name 值。这是我在 settings.py 中的 CONTEXT_PROCESSORS:

CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)

这是我的模板标签代码:
from django import template
register = template.Library()

@register.simple_tag(takes_context=True)
def full_static_url(context, url):
request = context['request']
scheme = 'http'
if request.is_secure:
scheme += 's'
return scheme + '://' + request.site_name + context['STATIC_URL'] + url

在我的 View 代码中,我正在使用新的渲染快捷方式,如下所示:
return render(request, 'myapp/mytemplate.html', {'foo':bar})

我在模板中这样称呼它:
{% full_static_url "images/logo.gif" %}

问题是,当它到达 行时request = context['request'] 它抛出一个 KeyError 因为“请求”不在上下文中。

我在这里做错了什么?

完整的回溯是:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
111. response = callback(request, *callback_args, **callback_kwargs)
File "C:\Projects\blah\blah\myapp\views\myview.py" in manifestcosts
44. return render(request, 'myapp/mytemplate.html', {'foo':bar})
File "C:\Python27\lib\site-packages\django\shortcuts\__init__.py" in render
44. return HttpResponse(loader.render_to_string(*args, **kwargs),
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
176. return t.render(context_instance)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
140. return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
134. return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
823. bit = self.render_node(node, context)
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
74. return node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
185. nodelist.append(node.render(context))
File "C:\Python27\lib\site-packages\django\template\base.py" in render
1107. return func(*resolved_args, **resolved_kwargs)
File "C:\Projects\blah\blah\myapp\templatetags\mytags.py" in full_static_url
25. request = context['request'] #TODO this fails with an KeyError, don't know why
File "C:\Python27\lib\site-packages\django\template\context.py" in __getitem__
54. raise KeyError(key)

Exception Type: KeyError at /myapp/myurl/110505081136179000/
Exception Value: 'request'

最佳答案

解决此问题的正确方法是添加 TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",)在您的 settings.py 文件中。

确保导入 TEMPLATE_CONTEXT_PROCESSORS首先与 from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS否则将无法正常工作。

关于django 自定义模板标签未在上下文中收到请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10288868/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com