Django context must be a dict ranther than Context

2023-05-16,,

1.1

错误描述

TypeError at /time/
context must be a dict rather than Context.
Request Method: GET
Request URL: http://127.0.0.1:8000/time/
Django Version: 2.0.5
Exception Type: TypeError
Exception Value:
context must be a dict rather than Context.
Exception Location: E:\Python\djone\venv\lib\site-packages\django\template\context.py in make_context, line 274
Python Executable: E:\Python\djone\venv\Scripts\python.exe
Python Version: 3.6.5
Python Path:
['E:\\Python\\djone\\mysite',
'E:\\Python\\djone\\venv\\Scripts\\python36.zip',
'C:\\Users\\daixiyu\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\daixiyu\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\daixiyu\\AppData\\Local\\Programs\\Python\\Python36',
'E:\\Python\\djone\\venv',
'E:\\Python\\djone\\venv\\lib\\site-packages',
'E:\\Python\\djone\\venv\\lib\\site-packages\\setuptools-28.8.0-py3.6.egg',
'E:\\Python\\djone\\venv\\lib\\site-packages\\pip-9.0.1-py3.6.egg']
Server time: Fri, 25 May 2018 23:27:35 +0000

代码

def current_datetime(request):
now = datetime.datetime.now()
t = get_template('current_datetime.html')
html = t.render(Context({'current_date': now}))
return HttpResponse(html)

分析

问题出在 t.render() 上 在Django2.0.5中

get_template()返回的Template对象的render方法上,让我们看一下render方法的源码

def render(self, context=None, request=None):
context=make_context(context,request,autoescape=self.backend.engine.autoescape)
try:
return self.template.render(context)
except TemplateDoesNotExist as exc:
reraise(exc, self.backend)

看第二行,调用了make_context(), 再看 make_context() 的源码

def make_context(context, request=None, **kwargs):
"""
Create a suitable Context from a plain dict and optionally an HttpRequest.
"""
if context is not None and not isinstance(context, dict):
raise TypeError('context must be a dict rather than %s.' % context.__class__.__name__)
if request is None:
context = Context(context, **kwargs)
else:
# The following pattern is required to ensure values from
# context override those from template context processors.
original_context = context
context = RequestContext(request, **kwargs)
if original_context:
context.push(original_context)
return context

看到第五行,此时会检查context是否为一个字典,目的是在随后为了使用context创建一个Context实例

结论

不要给Template对象的render()方法传递Context对象,其会使用传入的字典,自动创建一个Context对象,以供使用

Django context must be a dict ranther than Context的相关教程结束。

《Django context must be a dict ranther than Context.doc》

下载本文的Word格式文档,以方便收藏与打印。