Django utf8 model with obsolete database

I have an outdated latin-encoded database. I do not have access to change it to utf8. When I read the values ​​from the model, I get distorted text.

I tried using name.decode ('utf-8'), but it throws a unicode error:

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

name.encode ('utf-8') does not work either.

+2
source share
2 answers

If you have access to your settings.py file, you can change the settings to indicate that your database uses "latin1".

The following is an example configuration of "DATABASES" in the 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 a similar problem earlier, see the link here Django database encoding problem

+2
u = unicode(name,'latin-1')
print u.encode('utf-8')
+1

Source: https://habr.com/ru/post/1619861/


All Articles