Django 2.2.3报错:UnicodeDecodeError: ‘gbk’ codec can’t decode byte 0xa6 in position 9737: ill…

本文详细介绍了如何在Django项目中正确使用模板功能,并通过具体示例解释了常见错误及其解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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/,结果成功运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值