Tha*_*ing 3 django django-templates
我正在使用django 1.4并尝试将本文末尾描述的代码转换为自定义标签.这意味着我需要访问请求中的is_secure和site_name值.这是settings.py中的我的CONTEXT_PROCESSORS:
CONTEXT_PROCESSORS = (
'django.core.context_processors.request',
'django.contrib.auth.context_processors.auth',
)
Run Code Online (Sandbox Code Playgroud)
这是我的模板标记代码:
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
Run Code Online (Sandbox Code Playgroud)
在我的视图代码中,我使用了新的渲染快捷方式,如下所示:
return render(request, 'myapp/mytemplate.html', {'foo':bar})
Run Code Online (Sandbox Code Playgroud)
我在模板中这样称呼它:
{% full_static_url "images/logo.gif" %}
Run Code Online (Sandbox Code Playgroud)
问题是,当它到达行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'
Run Code Online (Sandbox Code Playgroud)
lit*_*ium 10
解决此问题的正确方法是添加TEMPLATE_CONTEXT_PROCESSORS += ("django.core.context_processors.request",)settings.py文件.
确保进口TEMPLATE_CONTEXT_PROCESSORS与第一from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS,否则将无法正常工作.
| 归档时间: |
|
| 查看次数: |
6712 次 |
| 最近记录: |