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")
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
#
# * Character Set
#
character_set_server = utf8mb4
collation_server = utf8mb4_unicode_ci
- 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';
Run the generated
ALTER
statementsRestart
MySQL
:
/etc/init.d/mysql restart
Django
- Add the
charset
option withutf8mb4
value to your database settings:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
# ...
"OPTIONS": {
"charset": "utf8mb4",
},
},
}
- Restart your application server
Done, now you can store Emojis in your database! 🚀
Top comments (0)