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的更多相关文章

  1. 在Django中template遇到 "context must be a dict rather

    原代码: # 使用模板文件 # 1.加载模板文件,获取一个模板文件 temp = loader.get_template('booktest/index.html') # 2.定义模板上下文:给模板文 ...

  2. org.springframework.web.context.support.XmlWebApplicationContext.refresh Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreatio

    错误异常: 11-Apr-2019 18:07:14.006 警告 [RMI TCP Connection(5)-127.0.0.1] org.springframework.web.context. ...

  3. Android Context完全解析,你所不知道的Context的各种细节

    Context相信所有的Android开发人员基本上每天都在接触,因为它太常见了.但是这并不代表Context没有什么东西好讲的,实际上Context有太多小的细节并不被大家所关注,那么今天我们就来学 ...

  4. golang语言中的context详解,Go Concurrency Patterns: Context

    https://blog.golang.org/context Introduction In Go servers, each incoming request is handled in its ...

  5. Django查询数据库返回字典dict数据

    个人观点: 个人认为,在Django项目中, 开发团队为了让使用该框架的用户都使用自带的序列化功能,从而让框架中的SQL返回值很不直观,对于直接使用SQL语句的用户很犯难. 解决: from djan ...

  6. 什么时候用Application的Context,什么时候用Activity的Context

    单例模式用application的context 如果我们在Activity A中或者其他地方使用Foo.getInstance()时,我们总是会顺手写一个『this』或者『mContext』(这个变 ...

  7. SpringMVC常见问题Error configuring application listener of class org.springframework.web.context.ContextLoaderListenejava.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

    六月 20, 2018 9:43:34 下午 org.apache.catalina.core.StandardContext listenerStart 严重: Error configuring ...

  8. django 快速搭建blog(三)

    http://www.cnblogs.com/fnng/p/3737964.html 引用自此博客 创建blog的公共部分 从Django的角度看, 一个页面 具有三个典型的组件: 一个模板(temp ...

  9. django 模板context的理解

    context作为view与template之间的桥梁,理解它的工作原理对于djagno的模板工作机制至关重要. class ContextDict(dict):#上下文词典,由词典可以通过conte ...

随机推荐

  1. CSS过渡时间

    CSS过渡时间 基础知识 在了解CSS过渡时间之前,你应该先了解一下CSS的变形动画,可以参考之前的一篇博客. 我们的元素在属性发生变化时,如果没有特地的为它设置过渡时间,整个变化过程其实是以毫秒级别 ...

  2. LeetCode 85 | 如何从矩阵当中找到数字围成的最大矩形的面积?

    本文始发于个人公众号:TechFlow,原创不易,求个关注 今天是LeetCode专题53篇文章,我们一起来看看LeetCode中的85题,Maximal Rectangle(最大面积矩形). 今天的 ...

  3. WEB前端常见受攻击方式及解决办法

    一个网站建立以后,如果不注意安全方面的问题,很容易被人攻击,下面就讨论一下几种漏洞情况和防止攻击的办法. 一.SQL注入 所谓SQL注入,就是通过把SQL命令插入到Web表单提交或输入域名或页面请求的 ...

  4. 前端学习(十):CSS选择器

    进击のpython ***** 前端学习--CSS选择器 每一条CSS样式声明由两部分组成: 选择器{ 样式: } 在CSS中{}之前的部分就是"选择器","选择器&qu ...

  5. rpm -ivh vsftpd-3.0.2-22.el7.x86_64.rpm出现error: open of vsftpd-3.0.2-22.el7.x86_64.rpm failed: No such file or directory的解决方法

    情况一: 出现如图问题, 我当时的问题是通过安装rpmbuild工具软件解决的 以前制作rpm时,没有遇到过这个问题,几经搜索也没有解决.后来发现当前的centos没有安装 rpmbuild 工具软件 ...

  6. linux杂七杂八

    反斜线\用于命令换行,在\之后应该直接回车换行 [root@CentOS7- ~]# cp /etc/sysconfig/network-scripts/ifcfg-ens33\ > /tmp/ ...

  7. NACOS安装和配置

    安装包nacos-server-1.1.4.tar.gz 环境 JDK1.8 上传及解压 [root@centos7- ~ ]# mkdir -p /cslc/nacos #通过SFTP将安装包上传至 ...

  8. 性能测试必备知识(7)- 深入理解“CPU 使用率”

    做性能测试的必备知识系列,可以看下面链接的文章哦 https://www.cnblogs.com/poloyy/category/1806772.html 回顾 CPU 使用率是单位时间内 CPU 使 ...

  9. 1-Numpy的通用函数(ufunc)

    一.numpy“通用函数”(ufunc)包括以下几种: 元素级函数(一元函数):对数组中的每个元素进行运算 数组级函数:统计函数,像聚合函数(例如:求和.求平均) 矩阵运算 随机生成函数 常用一元通用 ...

  10. Python time gmtime()方法

    描述 Python time gmtime() 函数将一个时间戳转换为UTC时区(0时区)的struct_time,高佣联盟 www.cgewang.com 可选的参数sec表示从1970-1-1以来 ...