我正在使用 django 1.4 并尝试将本文末尾描述的代码转换为 customtag。这意味着我需要访问请求中的 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
在我的视图代码中,我正在使用新的渲染快捷方式,如下所示:
return render(request, 'myapp/mytemplate.html', {'foo':bar})
我在模板中这样称呼它:
{% full_static_url "images/logo.gif" %}
问题是,当它到达行request = context['request']时,它会抛出一个 KeyError ,因为 'request' 不在上下文中。
我在这里做错了什么?
完整的追溯是:
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'