Django:非ASCII字符 [英] Django: Non-ASCII character
问题描述
我的Django视图/模板无法处理特殊字符。以下简单的视图因为ñ而失败。我收到以下错误:
文件中的非ASCII字符'\xf1'
def test(request):
return HttpResponse('español')
是否有一些一般的设置,我需要设置?如果我不得不单独处理所有字符串会很奇怪:非美国字母很常见! / p>
编辑
这是为了回应下面的评论,仍然失败:(
我按照Gabi的建议,将编辑评论添加到我的视图和元信息到我的html。
现在我上面的例子没有给出错误,但ñ显示不正确。
我尝试过 return render_to_response('tube / mysite.html',{s:'español '})
。没有错误,但它不会dislay(如果s = hello则会这样做)html页面上的其他信息显示正常。
$ b $我尝试将'español'硬编码到我的H中TML并且失败:
UnicodeDecodeError'utf8'编解码器无法解码字节0xf。
我试着用你的字符串前面:
SyntaxError(unicode error)'utf8'codec无法解码字节0xf1
这是否有帮助? ?
您是否在脚本开头有这样的内容:
# - * - 编码:utf-8 - * -
...?
请参阅: http://www.python.org/dev/peps/pep-0263/
编辑:对于第二个问题,它是关于html编码。把它放在你的html页面的头部(你应该发送请求作为html页面,否则我不认为你将能够正确地输出该字符):
< meta http-equiv =Content-Typecontent =text / html; charset = utf-8/>
My Django View/Template is not able to handle special characters. The simple view below fails because of the ñ. I get below error:
Non-ASCII character '\xf1' in file"
def test(request):
return HttpResponse('español')
Is there some general setting that I need to set? It would be weird if I had to handle all strings separately: non-American letters are pretty common!
EDIT This is in response to the comments below. It still fails :(
I added the coding comment to my view and the meta info to my html, as suggested by Gabi.
Now my example above doesn't give an error, but the ñ is displayed incorrectly.
I tried return render_to_response('tube/mysite.html', {"s": 'español'})
. No error, but it doesn't dislay (it does if s = hello). The other information on the html page displays fine.
I tried hardcoding 'español' into my HTML and that fails:
UnicodeDecodeError 'utf8' codec can't decode byte 0xf.
I tried with the u in front of the string:
SyntaxError (unicode error) 'utf8' codec can't decode byte 0xf1
Does this help at all??
Do you have this at the beginning of your script:
# -*- coding: utf-8 -*-
...?
See this: http://www.python.org/dev/peps/pep-0263/
EDIT: For the second problem, it's about the html encoding. Put this in the head of your html page (you should send the request as an html page, otherwise I don't think you will be able to output that character correctly):
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
这篇关于Django:非ASCII字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!