How to use Emojis in a Python + Django + MySQL project

fabiocaccamo

Fabio Caccamo

Posted on May 30, 2023

How to use Emojis in a Python + Django + MySQL project

Did you ever received an error like this while saving some text containing Emojis to the database?

DataError at /admin/myapp/mymodel/1/change/
(1366, "Incorrect string value: '\\xF0\\x9F\\x99...' for column 'text' at row 1")
Enter fullscreen mode Exit fullscreen mode

To overcome this problem you have to change the database and application charset to utf8mb4:

MySQL

  • Backup your database

  • Edit MySQL conf and add/set the charset settings:

nano /etc/mysql/mysql.conf.d/mysqld.cnf
Enter fullscreen mode Exit fullscreen mode
#
# * Character Set
#
character_set_server = utf8mb4
collation_server = utf8mb4_unicode_ci
Enter fullscreen mode Exit fullscreen mode
  • Update database tables character-set to utf8mb4:
SELECT CONCAT('ALTER TABLE ', table_name, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;') AS alter_statement
FROM information_schema.tables
WHERE table_schema = 'mydatabasename';
Enter fullscreen mode Exit fullscreen mode
  • Run the generated ALTER statements

  • Restart MySQL:

/etc/init.d/mysql restart
Enter fullscreen mode Exit fullscreen mode

Django

  • Add the charset option with utf8mb4 value to your database settings:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        # ...
        "OPTIONS": {
            "charset": "utf8mb4",
        },
    },
}
Enter fullscreen mode Exit fullscreen mode
  • Restart your application server

Done, now you can store Emojis in your database! 🚀

💖 💪 🙅 🚩
fabiocaccamo
Fabio Caccamo

Posted on May 30, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related