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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay