我无法弄清楚为什么我在 Django 1.11 和RenderContext
. 我在这里真的需要帮助。这是我在 1.11 的官方文档中使用的代码:
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.template import loader
def ip_address_processor(request):
return {'ip_address': request.META['REMOTE_ADDR']}
def view_2(request):
template = loader.get_template('template2.html')
ctx = RequestContext(request, {
'title': 'Your IP Address',
}, [ip_address_processor])
return HttpResponse(template.render(ctx))
还有我的简单模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Test
{{ title }}: {{ ip_address }}
</body>
</html>
这会导致以下错误:
Internal Server Error: /view2/
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
response = get_response(request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\null\PycharmProjects\project1\project1\views.py", line 48, in view_2
return template.render(c)
File "C:\Python27\lib\site-packages\django\template\backends\django.py", line 64, in render
context = make_context(context, request, autoescape=self.backend.engine.autoescape)
File "C:\Python27\lib\site-packages\django\template\context.py", line 287, in make_context
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
TypeError: context must be a dict rather than RequestContext.
[07/Aug/2017 23:52:49] "GET /view2/ HTTP/1.1" 500 72701
这对我来说很奇怪,因为以下代码有效:
from django.http import HttpResponse
from django.template import RequestContext, Template
from django.template import loader
def ip_address_processor(request):
return {'ip_address': request.META['REMOTE_ADDR']}
def view_2(request):
template = Template('{{ title }}: {{ ip_address }}')
ctx = RequestContext(request, {
'title': 'Your IP Address',
}, [ip_address_processor])
return HttpResponse(template.render(ctx))
通过覆盖 Template 对模板进行硬编码可以正常工作,但使用 django.template.loader.get_loader 导入它不会???我在这里真的很茫然。
我究竟做错了什么?模板正在做同样的事情。这真的让我从 1.11 回来了。以前你可以在 Django 1.8 中传递一个 context_instance ,它就可以工作了。即使使用 docs.djangoproject.com 上记录的示例,我似乎也无法在 1.11 中运行任何上下文处理器。只有当我调用 Template 并通过硬编码传递我的模板时,它才会起作用。