Thursday, March 24, 2011

Non-ascii string in verbose_name argument when declaring DB field in Django.

I declare this:

#This file is using encoding:utf-8
...
class Buddy(models.Model):
    name=models.CharField('ФИО',max_length=200)
    ...

... in models.py. manage.py syncdb works smoothly. However when I go to admin interface and try to add a new Buddy I catch a DjangoUnicodeDecodeError, which says: "'utf8' codec can't decode bytes in position 0-1: invalid data. You passed in '\xd4\xc8\xce' (<type 'str'<r;)".

I'm using sqlite3, so all strings are stored as bytestrings encoded in utf8 there. Django's encoding is also utf8. Seen django's docs on this topic, no idea.

UPD: Eventually I figured out what the problem was. It turned out to be that I'd saved my source in ANSI encoding.

Solution: I saved the source in UTF-8 and it worked wonders.

From stackoverflow
  • First, I would explicitly define your description as a Unicode string:

    class Buddy(models.Model):
        name=models.CharField(u'ФИО',max_len)
    

    Note the 'u' in u'ФИО'.

    Secondly, do you have a __unicode__() function defined on your model? If so, make sure that it returns a Unicode string. It's very likely you're getting this error when the Admin interface tries to access the unicode representation of the model, not when it's added to the database. If you're returning a non-unicode string from __unicode__(), it may cause this problem.

0 comments:

Post a Comment