Django Database Setup MySQL / MariaDB

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Django supports MySQL 5.5 and higher.

Make sure to have some packages installed:

$ sudo apt-get install mysql-server libmysqlclient-dev
$ sudo apt-get install python-dev python-pip              # for python 2
$ sudo apt-get install python3-dev python3-pip            # for python 3

As well as one of the Python MySQL drivers (mysqlclient beeing the recommended choice for Django):

$ pip install mysqlclient    # python 2 and 3
$ pip install MySQL-python   # python 2
$ pip install pymysql        # python 2 and 3

The database encoding can not be set by Django, but needs to be configured on the database level. Look for default-character-set in my.cnf (or /etc/mysql/mariadb.conf/*.cnf ) and set the encoding:

   [mysql]
   #default-character-set = latin1    #default on some systems.
   #default-character-set = utf8mb4   #default on some systems.
   default-character-set = utf8

   ...
   [mysqld]
   #character-set-server  = utf8mb4
   #collation-server      = utf8mb4_general_ci
   character-set-server  = utf8
   collation-server      = utf8_general_ci

Database configuration for MySQL or MariaDB

#myapp/settings/settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DB_NAME',
        'USER': 'DB_USER',
        'PASSWORD': 'DB_PASSWORD',
        'HOST': 'localhost',   # Or an IP Address that your database is hosted on
        'PORT': '3306',
        #optional:
        'OPTIONS': {
            'charset' : 'utf8',
            'use_unicode' : True,
             'init_command': 'SET '
                'storage_engine=INNODB,'
                'character_set_connection=utf8,'
                'collation_connection=utf8_bin'
                #'sql_mode=STRICT_TRANS_TABLES,'    # see note below
                #'SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED',
        },
        'TEST_CHARSET': 'utf8',
        'TEST_COLLATION': 'utf8_general_ci',
    }
}

If you are using Oracle's MySQL connector your ENGINE line should look like this:

'ENGINE': 'mysql.connector.django',

When you create a database, make sure that to specify the encoding and collation:

CREATE DATABASE mydatabase CHARACTER SET utf8 COLLATE utf8_bin

From MySQL 5.7 onwards and on fresh installs of MySQL 5.6, the default value of the sql_mode option contains STRICT_TRANS_TABLES. That option escalates warnings into errors when data is truncated upon insertion. Django highly recommends activating a strict mode for MySQL to prevent data loss (either STRICT_TRANS_TABLES or STRICT_ALL_TABLES). To enable add to /etc/my.cnf sql-mode = STRICT_TRANS_TABLES



Got any Django Question?