Django使用模板时,view中的代码如下:
view.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, RequestContext
# Create your views here.
# 定义视图函数
# 进行URL配置
# http://127.0.0.1:8000/index
def index(request): # 必须有参数
# return HttpResponse("不乱于心,不困于情, 不畏将来,不念过往。 如此。安好。")
# 使用模板文件
# 1.加载模板文件:去模板下获取HTML的内容,得到一个模板对象
temp = loader.get_template('lphapp/index.html')
# 2.定义模板上下文:向模板文件传递数据
context = RequestContext(request, {})
# 3.模板渲染:得到一个标准的HTML内容
res_html = temp.render(context)
# 4.返回给浏览器
return HttpResponse(res_html)
def index2(request): # 必须有参数
return HttpResponse("hello python")
运行服务后,访问http://127.0.0.1:8000/index/
结果浏览器出现:“A server error occurred. Please contact the administrator.”
不知道错在哪里,很是不便。
解决方法:
python安装路径\Lib\site-packages\django\views\debug.py ,打开后,修改约在 332 行处,将:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open() as fh:
修改为:
with Path(CURRENT_DIR, 'templates', 'technical_500.html').open(encoding='utf-8') as fh:
就会出现报错信息如下:
然后修改代码为:
view.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader, RequestContext
# Create your views here.
# 定义视图函数
# 进行URL配置
# http://127.0.0.1:8000/index
def index(request): # 必须有参数
# return HttpResponse("不乱于心,不困于情, 不畏将来,不念过往。 如此。安好。")
# 使用模板文件
# 1.加载模板文件:去模板下获取HTML的内容,得到一个模板对象
temp = loader.get_template('lphapp/index.html')
# 2.定义模板上下文:向模板文件传递数据
# context = RequestContext(request, {}) # 错误
context = {} # 必须为字典类型
# 3.模板渲染:得到一个标准的HTML内容
res_html = temp.render(context)
# 4.返回给浏览器
return HttpResponse(res_html)
def index2(request): # 必须有参数
return HttpResponse("hello python")
运行服务后,访问http://127.0.0.1:8000/index/,结果成功运行。