Storing Emojis with Django

I just ran into this issue on this site while trying to save content that contained an emoji character. It saved as “????”.

My database is able to store emoji fine, but I hadn’t changed the charset in my database connection, and apparently Django defaults to utf8. I needed to add ?charset=utf8mb4 to the end of my mysql connection url in settings.py:

DATABASES = {
    'default': 'mysql://mydatabaseuser:mypassword@127.0.0.1:3306/mydatabase?charset=utf8mb4',
}

or, if using a dict:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydatabase',
        'USER': 'mydatabaseuser',
        'PASSWORD': 'mypassword',
        'HOST': '127.0.0.1',
        'PORT': '5432',
        'OPTIONS': {
        	'charset': 'utf8mb4',
        }
    }
}

I’m not exactly sure what side effects this may have, as Django docs state

Django assumes that all databases use UTF-8 encoding. Using other encodings may result in unexpected behavior such as “value too long” errors from your database for data that is valid in Django. See the database specific notes below for information on how to set up your database correctly.

I think this will be ok, as it’s still utf-8, just using one more byte to store a character.