3

I have a legacy database with latin1 encoding. I do not have access to change it to utf8. When I read values from the model, I am getting garbled text.

I tried to use name.decode('utf-8') but it is throwing a unicode error:

 'ascii' codec can't encode characters in position 4-12: ordinal not in range(128)

name.encode('utf-8') doesnt work either.

wjh
  • 597
  • 2
  • 6
  • 18

2 Answers2

3

If you have access to your 'settings.py' file, then you can change the settings saying that your database is using 'latin1'.

Following is the example of the 'DATABASES' configuration in 'settings.py' file.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test_db',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': '',
        'PORT': '3306',
        'OPTIONS': {
                    'charset': 'latin1',
                    'use_unicode': True, },
    }, 
}

I had similar issue earlier, checkout the link here Django database charset issue

Community
  • 1
  • 1
Krishna Balan
  • 256
  • 4
  • 9
  • Thanks. This works. But do you have any idea how to set the charset for individual tables? Some of the tables use latin1 and some use utf-8. – wjh Mar 27 '13 at 08:08
  • AFAIK Django doesn't support setting charset for individual tables. But i guess there would be some way to do it. – Krishna Balan Mar 27 '13 at 09:11
1
u = unicode(name,'latin-1')
print u.encode('utf-8')
catherine
  • 22,492
  • 12
  • 61
  • 85