Python Django编码错误,非ASCII字符'\xe5';
你好, 我在Python Django中遇到了一个编码错误。 在my views.py中,我有以下内容:Python Django编码错误,非ASCII字符'\xe5';,python,django,view,encoding,Python,Django,View,Encoding,你好, 我在Python Django中遇到了一个编码错误。 在my 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(req
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)
谢谢大家。如果您阅读,它会清楚地说:
要定义源代码编码,必须在源文件中放置一个魔术注释,作为文件的第一行或第二行
(最初的提案说,如果有的话,它必须是#!)之后的第一行,但根据“第一行或第二行”规则,它可能更容易实施。)
实际的参考文档以不太友好但更严格的方式描述了相同的事情,例如和
文件后面出现的“魔术注释”不是魔术,它只是一个误导读者而不影响Python编译器的注释
适用于<代码>u'的UTF-8哈哈'是'\xe5\x93\x88\xe5\x93\x88'
,因此这些是文件中的字节。在最近的Python版本(包括2.7和所有3.x)中,默认编码总是ASCII,除非文件以UTF BOM开头(正如一些Microsoft编辑器所做的那样);即使在2.3-2.6中,它通常也是ASCII码;在早期版本中,它是拉丁-1。试图解释“\xe5\x93\x88\xe5\x93\x88”
将失败,出现您看到的异常情况。好了,给您:
将#-*-编码:utf-8-*-
放在文件顶部,它定义了反编码
报告说:
如果没有其他编码,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
...
希望有帮助不应该
#-*-编码:utf-8-*-
在文件的顶部吗?嗨,拉洛,你说得对。我把那条线放在上面后,它就起作用了。谢谢你。@lalo:写下来作为回答;如果你链接到文档并解释它,那几乎肯定是他的问题。同时,你确定源文件实际上保存为UTF-8文本,而不是Shift JIS吗?因为对Python撒谎(例如,获取一个Shift JIS文件并在头部添加一个UTF-8编码声明)并不能让它神奇地猜出你想要什么。(在这种情况下,我99%确定这与此无关,但您应该始终将这些信息放入问题中,以便我们不必猜测。)
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
...