DEV Community

Cover image for How to use Emojis in a Python + Django + MySQL project
Fabio Caccamo
Fabio Caccamo

Posted on

2

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! 🚀

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up