Search code examples
pythondjangotagsdjango-templatespython-unicode

Django non-ASCII chars in template tags values


I'm writing a custom Django template tag for a french application. My template tag takes a parameter which is a string:

{% mytag "Hello" %}

Is works perfect, but fails when trying to put some non-ASCII chars in the value.

How would you get this thing work:

{% mytag "Êtes-vous à Paris ?" %}

I got this error:

'ascii' codec can't encode character u'\xca' in position 0: ordinal not in range(128)

Unicode error hint

The string that could not be encoded/decoded was: Êtes-v

Thanks very much in advance!

EDIT: Python version is 2.7. Here is the code of the tag:

@register.simple_tag(takes_context=True)
def mytag(context, my_var):
    return "Here it is: {my_var}".format(my_var=my_var)

Solution

  • Try replacing

    return "Here it is: {my_var}".format(my_var=my_var)
    

    by

    return u"Here it is: {my_var}".format(my_var=my_var)
    

    In Python 2.7, "Here it is: {my_var}" is a str object, an encoded string, my_var is a unicode object, a decoded string, when formatting, Python will try to encode my_var so it matches the type of the formatting string. It does so using the ascii codec by default which does not support special characters.

    Adding the u before the formatting string makes it a unicode string, no encoding will take place during formatting.

    Since it looks like you might speak French, I advise you to read this article which is a great guide to encoding in Python.