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" />
Insert at the top of views.py
# -*- coding: utf-8 -*-
And add "u" before your string
my_str = u"plus de détails"
Solved!
You need the coding comment Gabi mentioned and also use the unicode "u" sign before your string :
return HttpResponse(u'español')
The best page I found on the web explaining all the ASCII/Unicode mess is this one : http://www.stereoplex.com/blog/python-unicode-and-unicodedecodeerror
Enjoy!
Set DEFAULT_CHARSET to 'utf-8'
in your settings.py file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With