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對象,以供使用