Django context must be a dict ranther than Context
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中template遇到 "context must be a dict rather
原代码: # 使用模板文件 # 1.加载模板文件,获取一个模板文件 temp = loader.get_template('booktest/index.html') # 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. ...
- Android Context完全解析,你所不知道的Context的各种细节
Context相信所有的Android开发人员基本上每天都在接触,因为它太常见了.但是这并不代表Context没有什么东西好讲的,实际上Context有太多小的细节并不被大家所关注,那么今天我们就来学 ...
- golang语言中的context详解,Go Concurrency Patterns: Context
https://blog.golang.org/context Introduction In Go servers, each incoming request is handled in its ...
- Django查询数据库返回字典dict数据
个人观点: 个人认为,在Django项目中, 开发团队为了让使用该框架的用户都使用自带的序列化功能,从而让框架中的SQL返回值很不直观,对于直接使用SQL语句的用户很犯难. 解决: from djan ...
- 什么时候用Application的Context,什么时候用Activity的Context
单例模式用application的context 如果我们在Activity A中或者其他地方使用Foo.getInstance()时,我们总是会顺手写一个『this』或者『mContext』(这个变 ...
- 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 ...
- django 快速搭建blog(三)
http://www.cnblogs.com/fnng/p/3737964.html 引用自此博客 创建blog的公共部分 从Django的角度看, 一个页面 具有三个典型的组件: 一个模板(temp ...
- django 模板context的理解
context作为view与template之间的桥梁,理解它的工作原理对于djagno的模板工作机制至关重要. class ContextDict(dict):#上下文词典,由词典可以通过conte ...
随机推荐
- Notion笔记工具免费开通教育许可
修改为edu邮箱 如果咱注册的时候就用的咱的edu,就不用看这部分啦! 点击[Get free Education plan],提示要修改咱的注册邮箱! 开通咱的教育版 最后附上ac邮箱两枚 http ...
- Spring事务源码分析专题(一)JdbcTemplate使用及源码分析
Spring中的数据访问,JdbcTemplate使用及源码分析 前言 本系列文章为事务专栏分析文章,整个事务分析专题将按下面这张图完成 对源码分析前,我希望先介绍一下Spring中数据访问的相关内容 ...
- 基于python实现查询ip地址来源
接口调用方法是在url后面直接加上IP地址. url = 'http://freeapi.ipip.net/218.192.3.42' #中文免费 url2 = 'http://ip-api.com/ ...
- centos7 安装 isign
centos应该自带python和openssl,这两个就不用装了, 先安装zip和git yum install -y unzip zip yum install git 然后克隆代码: https ...
- ActiveMQ【CVE-2016-3088】上传公钥实现sssh免密登录
Apache-ActiveMQ是apache旗下的消息中间件,至今为止还是有较多的甲方爸爸们,还在使用该中间件.据了解,Apache-ActiveMQ中间件有2个厉害的CVE,一个是CVE-2016- ...
- 【评价指标】详解F1-score与多分类MacroF1&MicroF1
文章来自:一个宝藏微信公众号[机器学习炼丹术] 基本概念 首先,要背住的几个概念就是:accuracy,precision,recal, TP,FP,TN,FN TP:true positive.预测 ...
- 各版本arm-gcc区别与安装【转】
转自:https://www.jianshu.com/p/fd0103d59d8e arm-linux-gcc.arm-none-eabi-gcc.arm-eabi-gcc.arm-none-linu ...
- 线程_使用multiprocessing启动一个子进程及创建Process 的子类
from multiprocessing import Process import os # 子进程执行的函数 def run_proc(name): print("子进程运行中,名称:% ...
- 《闲扯Redis九》Redis五种数据类型之Set型
一.前言 Redis 提供了5种数据类型:String(字符串).Hash(哈希).List(列表).Set(集合).Zset(有序集合),理解每种数据类型的特点对于redis的开发和运维非常重要. ...
- Codeforces Round #649 (Div. 2) E. X-OR 交互 二进制 随机 期望
LINK:X-OR 本来是应该昨天晚上发的 可是昨天晚上 做这道题 写了一个分治做法 一直wa 然后查错 查不出来 心态崩了 想写对拍 发现交互库自己写不出来. 一系列sb操作 == 我都醉了. 今天 ...