Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Non-ASCII character

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??

like image 429
dkgirl Avatar asked Jan 08 '11 17:01

dkgirl


4 Answers

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" />
like image 134
Gabi Purcaru Avatar answered Nov 05 '22 01:11

Gabi Purcaru


Insert at the top of views.py

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

And add "u" before your string

my_str = u"plus de détails"

Solved!

like image 41
Cedric Avatar answered Nov 05 '22 01:11

Cedric


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!

like image 8
Dominique Guardiola Avatar answered Nov 05 '22 01:11

Dominique Guardiola


Set DEFAULT_CHARSET to 'utf-8' in your settings.py file.

like image 3
rubayeet Avatar answered Nov 05 '22 00:11

rubayeet