Python Django编码错误,非ASCII字符'\ xe5'

 周树草 发布于 2023-02-08 18:39

嗨,我遇到了Python Django的编码错误.在我的views.py中,我有以下内容:

from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
# Create your views here.

def hello(request):
    name = 'Mike'
    html = 'Hi %s, this seems to have !!!!worked!' % name
    return HttpResponse(html)

def hello2(request):
    name = 'Andrew'
    html = 'Hi %s, this seems to have !!!!worked!' % name
    return HttpResponse(html)

# -*- coding: utf-8 -*-
def hello3_template(request):
    name = u'??'
    t = get_template('hello3.html')
    html = t.render(Context({'name' : name}))
    return HttpResponse(html)

我收到以下错误:

/ hello3_template /中的SyntaxError 第19行的文件D:\ WinPython-32bit-2.7.5.3\django_test\article\views.py中的非ASCII字符'\ xe5',但未声明编码; 有关详细信息,请访问http://www.python.org/peps/pep-0263.html(views.py,第19行)

我查了那个链接,但我仍然对如何解决它感到困惑.

你能帮忙吗?谢谢,小熊

正如lalo指出的那样,以下行必须在顶部

# -*- coding: utf-8 -*-

谢谢你们.

1 个回答
  • 那么,你在这里:

    放在# -*- coding: utf-8 -*-文件顶部,它定义de编码.

    该文件说:

    如果没有给出其他编码提示,Python将默认为ASCII作为标准编码.

    To define a source code encoding, a magic comment must
    be placed into the source files either as first or second
    line in the file, such as:
    

    所以,你的代码必须开始:

    # -*- coding: utf-8 -*-
    from django.shortcuts import render
    from django.http import HttpResponse
    from django.template.loader import get_template
    ...
    

    希望有所帮助

    2023-02-08 18:41 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有