8

MySQL 5.5.35 Django 1.6.1

In order to support emoticons in the DB, I have configured in my django settings:

'OPTIONS': {'charset': 'utf8mb4'}

On MySQL connection, I get this error: LookupError: unknown encoding: utf8mb4

How should I configure Django/MySQL in order to support utf8mb4?

Amit Talmor
  • 5,376
  • 3
  • 21
  • 25

4 Answers4

14

https://code.djangoproject.com/ticket/18392#comment:10

As a workaround, you can make python understand 'utf8mb4' as an alias for 'utf8':

import codecs
codecs.register(lambda name: codecs.lookup('utf8') if name == 'utf8mb4' else None)
Tim Tisdall
  • 8,670
  • 3
  • 41
  • 70
  • @ChrisSH - I don't remember where I put it... It needs to run once and probably before it makes the DB connection. Maybe in the `__init__.py` or in `settings.py`? – Tim Tisdall Jun 06 '17 at 19:04
  • this is also worked for sqlalchemy to connect mysql database. – Günay Gültekin Nov 21 '17 at 07:30
  • @GünayGültekin - I think the [issue is specific to the db adapter used with sqlalchemy](http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#charset-selection) and not sqlalchemy itself. Which adapter are you using that this works with? – Tim Tisdall Nov 21 '17 at 13:14
  • @GünayGültekin - have you tried passing the [`charset` arg as shown in the docs](http://docs.sqlalchemy.org/en/latest/dialects/mysql.html#charset-selection)? It seems like your adapter should support `utf8mb4` out-of-the-box (according to the docs). – Tim Tisdall Nov 21 '17 at 13:36
9

If you really need utf8mb4, follow the steps in https://mathiasbynens.be/notes/mysql-utf8mb4, and make sure your python package "MySQL-python" version is >= 1.2.5 !

nanchen
  • 91
  • 1
  • 1
0

Fast and easy way.

connection = mysql.connector.connect(user='username',
                                   password='mypass',
                                    host='localhost',
                                     database='mydb',
                                       use_pure=True,
                                      charset='utf8'
                                      )
Meikel
  • 21
  • 1
0

This worked in my case (MySQL 5.7 + Django 3.1):

Configure Django:

'ENGINE': 'django.db.backends.mysql',
'OPTIONS': {
 'charset': 'utf8mb4' 
}

Configure MySQL database

  1. make sure all db tables are using InnoDB storage engine (this is important; the next step will probably fail if you skip it)
  2. change the Collation for all your tables to utf8mb4_general_ci

Test it:

Try to save the poop character in your db .

addmoss
  • 454
  • 5
  • 12