Swipe left or right to navigate to next or previous post

How to add unicode support in mysql and django

29 Mar 2022 . category: Django . Comments
#Django #MySQL

Ultimate guide to  add unicode support in mysql and django

This blog post is about how to add unicode support in Django in MySQL database.

Create a database

To support the unicode, we need to create the database that support the unicode. For this, create a database with following command in MySQL commandline

    create database my_db_name character set utf8mb4;

Update database setting

Since, the blog focused on the mysql, the engine value is obvious. Add the additional settings on options for unicode support. The database setting is usually set on .env file on the root folder of the project or it could be on the settings.py file

    DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        ...
        'OPTIONS': {
                    'charset': 'utf8mb4',
                    'use_unicode': True, },
        },
    }

Update the mysql configuration file

Open the my.cnf file located in /etc/mysql/ folder

    sudo nano /etc/mysql/my.cnf

Update the configuration details as below:

    [client]
    default-character-set = utf8mb4
    
    [mysql]
    default-character-set = utf8mb4
    
    [mysqld]
    character-set-client-handshake = FALSE
    character-set-server = utf8mb4
    collation-server = utf8mb4_unicode_ci

Changes on Existing database

There are chances that you want to set the unicode support for existing database. You can update the mysql database setting by running the following code in mysql command line tool.

To run the command, first login to the command line tool by using:

    mysql -u mysql_user -p

Enter password and hit enter. After successful login, run the following command

    ALTER DATABASE my_db_name CHARACTER SET = utf8mb4 COLLATE utf8mb4_unicode_ci;

Tapan B.K. | Full Stack Software Engineer

Tapan B.K. is Full Stack Software Engineer. In his spare time, Tapan likes to watch movies, visit new places.