Sunday, October 28, 2012

Django request with unicode strings wrongly UTF-8 encoded

I'm having some trouble making my website compatible with accented characters (french website).

I have a form where some field values can be with accented chars: "Coupé" for instance.

My URL looks like this:

http://localhost:8080/recherches/s?marque=Audi&modeles=A5+Coup%C3%A9

In my django view I do something like this:

def search(request):    logger = logging.getLogger('custom')    criteria_form = CriteriaForm(request.GET or None)    logger.debug("search")    logger.debug(request.GET)

And what I get in my logs is:

<QueryDict: {u'marque': [u'Audi'], u'modeles': [u'A5 Coup\xc3\xa9']}>

If I query my database with this variable "modeles", I get an error:

>>> mo = u'A5 Coup\xc3\xa9'  >>> Vehicule.objects.filter(valid=True, modele=mo)[0].marque.name  Traceback (most recent call last):    File "<console>", line 1, in <module>    File "/Library/Python/2.7/site-packages/django/db/models/query.py", line 211, in __getitem__      return list(qs)[0]  IndexError: list index out of range

Things work if I query the database with the utf-8 version:

>>> mo = 'A5 Coup\xc3\xa9'  >>> Vehicule.objects.filter(valid=True, modele=mo)[0].marque.name  u'Audi'

So I think (but I might be wrong) that my problem comes from the fact that my variable is utf8 and then encoded with unicode.

How comes this is encoded that way?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/qOX6yFHhnaYJ.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment