Python Django编码错误,非ASCII字符'\xe5' [英] Python Django Encoding Error, Non-ASCII character '\xe5'

查看:218
本文介绍了Python Django编码错误,非ASCII字符'\xe5'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我遇到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 = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % name
    return HttpResponse(html)

def hello2(request):
    name = 'Andrew'
    html = '<html><body>Hi %s, this seems to have !!!!worked!</body></html>' % 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
非ASCII字符'\xe5'在文件D:\WinPython-32bit-2.7.5.3\django_test\article\views.py在第19行,但没有编码声明;请参阅 http://www.python.org/peps/pep-0263.html详细信息(views.py,第19行)

SyntaxError at /hello3_template/

Non-ASCII character '\xe5' in file D:\WinPython-32bit-2.7.5.3\django_test\article\views.py on line 19, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details (views.py, line 19)

我查找该链接,但我仍然对如何解决它感到困惑。

I look up that link, but I am still puzzled on how to resolve it.

你能帮忙吗?
谢谢,
smallbee

Could you help? Thanks, smallbee

正如lalo指出,以下行必须位于顶部

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

谢谢,所有。

推荐答案

在这里你是:

# - * - 编码:utf-8 - * - ,它定义de编码。

Put # -*- coding: utf-8 -*- at top of file, it define de encoding.

docs 说:


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

Python will default to ASCII as standard encoding if no other encoding hints are given.

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:


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

So, you code must begin:

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

希望帮助

这篇关于Python Django编码错误,非ASCII字符'\xe5'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆