How to store emoji expressions in django mysql | Solve the problem of failure to store emoji expressions in django
3 min
Ankaj Gupta
July 09, 2021

How to store emoji expressions in django mysql | Solve the problem of failure to store emoji expressions in django

# Common problem

The error information of storing emoji expressions in table intelligence in django + mysql is:

In Django, django.db.utils.OperationalError: (1366, "Incorrect string value: '\\xF0\\x9F\\x90\\xA6 \\xF0...' for column 'description' at row 1").

# Reason

UTF-8 encoding may be two, three, or four bytes, Emoji expressions are 4-bytes, and MySql utf8 encoding is up to 3-bytes, so the data can't be inserted.

# Solution :

Convert Mysql encoding from utf8 to utf8mb4. The detailed description is as follow steps:

# Settings in MySql:

Step 1 : Modify the character set of the database:

  • ALTER DATABASE database_name CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci;

Step 2 : Use the database that currently needs character set modification:

  • use database_name;

Step 3 : Modify the character set of the table:

  • ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Step 4 : Modify the character set of the column:

  • ALTER TABLE table_name CHANGE field_name  VARCHAR(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

# Settings in django:

Step 5 : And finally, modify the code in settings.py as follows:

 ➤ Code: settings.py (MySql)

  1. DATABASES = {
    'default': {
    ...,
    # other settings
    'OPTIONS':{
    'charset': 'utf8mb4', # support emoji
    }
    }
    }


    """ DATABASES={
    'default':{
    'ENGINE' : 'django.db.backends.mysql',
    'NAME' : 'your-db-name',
    'USER' : 'user_name',
    'PASSWORD' : 'your-db-password',
    'HOST' : 'localhost',
    'PORT' : '3306',
    'OPTIONS' : {
    'charset : 'utf8mb4',
    }
    } """
django django and mysql

Related Posts