Python 常见问题 之 TypeError: context must be a dict rather than RequestContext. (Django)
Python 常见问题 之 TypeError: context must be a dict rather than RequestContext. (Django)
目录
Python 常见问题 之 TypeError: context must be a dict rather than RequestContext. (Django)
一、简单介绍
二、问题现象
三、问题解决的办法之一
一、简单介绍
Python是一种跨平台的计算机程序设计语言。是一种面向对象的动态类型语言,最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。Python是一种解释型脚本语言,可以应用于以下领域: Web 和 Internet开发、科学计算和统计、人工智能、教育、桌面界面开发、软件开发、后端开发、网络爬虫。
本节介绍,在学习 django 框架的时候,由于django 版本更新,接口更新,再进行 Views 获取对应页面显示的时候报的错误。
二、问题现象
主要报错内容:TypeError: context must be a dict rather than RequestContext.
报错关键代码:
from django.http import HttpResponse # 导入模块
from django.template import loader, RequestContext
# Create your views here.
def my_render(request, template_path, context_dict={}):
"""使用模板文件"""
print('my_render')
# 加载模板文件,模板对象
temp = loader.get_template(template_path)
# 定义模板上下文
context = RequestContext(request, context_dict)
# 模板渲染:产生标准的 html 内容
res_html = temp.render(context)
# 返回给浏览器
return HttpResponse(res_html)
# 定义一个自己的返回View内容
def my_view(request):
# 使用自己编写的模板渲染函数(注意可能有报错)
return my_render(request, "myshop/my_view.html", {
"content": "Test模板变量", "list": list(range(10, 20))
})
三、问题解决的办法之一
从错误中可以看到提示context应该是一个字典类型,而不是一个RequestContext,由此可知,代码中context是一个RequestContext类的实例
所以,更改代码如下,把 context 作为 字典类型即可,然后运行OK,应该是 django 以前版本可以,后面新版本的django 接口更新了:
关键修改:context = context_dict
from django.http import HttpResponse # 导入模块
from django.template import loader, RequestContext
# Create your views here.
def my_render(request, template_path, context_dict={}):
"""使用模板文件"""
print('my_render')
# 加载模板文件,模板对象
temp = loader.get_template(template_path)
# 定义模板上下文
# context = RequestContext(request, context_dict)
context = context_dict
# 模板渲染:产生标准的 html 内容
res_html = temp.render(context)
# 返回给浏览器
return HttpResponse(res_html)
# 定义一个自己的返回View内容
def my_view(request):
# 使用自己编写的模板渲染函数(注意可能有报错)
return my_render(request, "myshop/my_view.html", {
"content": "Test模板变量", "list": list(range(10, 20))
})
其中 html 为:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>我的模板文件</title>
</head>
<body>
<h1>这是一个我的测试模板文件</h1>
测试使用模板变量:<br/>
{
{ content }}<br/>
<br/>
测试使用模板列表变量:<br/>
{
{ list }}<br/>
<br/>
测试使用模板 for 循环:<br/>
<ul>
{% for i in list %}
<li>{
{ i }}</li>
{% endfor %}
<ul>
<br/>
</body>
</html>
成功运行效果为:
还没有评论,来说两句吧...