views:

430

answers:

2

I have some french letters (é, è, à...) in a django template but when it is loaded by django, an UnicodeDecodeError exception is raised.

If I don't load the template but directly use a python string. It works ok.

Is there something to do to use unicode with django template?

+2  A: 

You are probably storing the template in a non-unicode encoding, such as latin-1. I believe Django assumes that templates are in UTF-8 by default (though there is a setting to override this).

Your editor should be capable of saving the template file in the UTF-8 encoding (probably via a dropdown on the save as page, though this may depend on your editor). Re-save the file as UTF-8, and the error should go away.

Brian
Pedantification: Latin-1 is not more "none-unicode" than UTF-8. Both are not unicode, but encodings. UTF-8 can encode all unicode characters of Unicode, and Latin-1 can't but they are still not unicode. It doesn't change the validity of your answer, I'm just being pedantic for no particular reason. ;)
Lennart Regebro
I'm all for being pedantic, but I should point out I used the phrase "non-unicode encoding", not just "non-unicode", which is accurate. UTF-8 is indeed an encoding (one of several) for unicode data, whereas latin-1 is not, as it cannot represent all possible unicode codepoints.
Brian
+1  A: 

This is from the Django unicode documentation related to your problem:

" But the common case is to read templates from the filesystem, and this creates a slight complication: not all filesystems store their data encoded as UTF-8. If your template files are not stored with a UTF-8 encoding, set the FILE_CHARSET setting to the encoding of the files on disk. When Django reads in a template file, it will convert the data from this encoding to Unicode. (FILE_CHARSET is set to 'utf-8' by default.)

The DEFAULT_CHARSET setting controls the encoding of rendered templates. This is set to UTF-8 by default. "

Andre Miller