我不能为我的生活弄清楚为什么我遇到了Django 1.11和RenderContext的问题。我真的需要帮助。这是我一直在玩从官方文档1.11代码:Django 1.11上下文处理器错误:TypeError:上下文必须是字典而不是RequestContext'
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))
通过覆盖模板对模板进行硬编码模板工作正常,但用django.template.loader.get_loader导入它不会?我真的很茫然。我究竟做错了什么?模板正在做同样的事情。这真的让我从1.11回来。它曾经是你可以在Django 1.8中传递一个context_instance,它刚刚工作。我似乎无法获得在1.11中运行的任何上下文处理器,即使使用docs.djangoproject.com上记录的示例。它只有在我打电话给Template并通过硬编码通过我的模板时才有效。
这是django 1.11的变化。不向后兼容。 https://docs.djangoproject.com/en/1.11/releases/1.11/#django-template-backends-django-template-render-prohibits-non-dict-context –
你也可以参考这张票https:// code .djangoproject.com/ticket/27722 – zaidfazil
Oh no :(! 您是否有正确的方式来处理1.11中的上下文处理器的任何资源?我认为定义一个函数然后返回一个字典值并通过在上下文中。 – user1601871