Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3+Django1.10+mysqlclient1.3.9: cannot save emoji characters

I got the error below in django when saving a field with emoji character in the admin panel.

OperationalError at /admin/core/message/add/ (1366, "Incorrect string value: '\xF0\x9F\x98\x9E \xF0...' for column 'name' at row 1")

I'm sure the database is ready for utf8mb4, because I can write/read these emoji character in phpmyadmin.

More, the saved emoji character displayed correctly in phpmyadmin but displays ??? in django output.

And in my another django project, the emoji plays well, till I just cannot find the difference between the two environment.

So what can be the problem when I save the same thing using python?

The problem is under django framework, so I want a solution that make django work.

like image 364
Alfred Huang Avatar asked Aug 26 '26 01:08

Alfred Huang


1 Answers

Setting DATABASE section in the settings.py with OPTIONS - charset solves this issue:

# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases

DATABASES = { 
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'myproject',
        'HOST': 'mysql',
        'USER': 'django',
        'PASSWORD': '******',
        'OPTIONS': {
            # !!!!!! THIS MATTERS !!!!!!
            'charset': 'utf8mb4',
        }
    },  
}

See documentation: https://docs.djangoproject.com/en/1.10/ref/settings/#charset

like image 145
Alfred Huang Avatar answered Aug 27 '26 14:08

Alfred Huang