SoFunction
Updated on 2024-12-19

Example of how to change the default database to mysql in Django

Django uses sqlite3 database by default, today I researched how to change it to the common mysql database.

Since the project uses python3, and MySQLdb does not support python3 version, pip install MySQLdb will report an error if you use the version.

Then I found out through Google that you can use pymysql instead of MySQLdb

1 Add the following code to the __init__.py file in the project root directory.

import pymysql
pymysql.install_as_MySQLdb()

2 Use mysqlclient instead of MySQLdb, installed as:

pip install mysqlclient

3 Change the project's configuration of the database to:

DATABASES = {
  'default': {
    'ENGINE': '',
    'NAME': 'test',
    'USER': 'username',
    'PASSWORD': 'passwd',
    'HOST': 'localhost',
    'PORT': '3306'
  }
}

4 Finally, with the python migrate command, Django will automatically create the appropriate tables in the database

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying polls.0001_initial... OK
  Applying sessions.0001_initial... OK

5 When creating the admin user, the following error was encountered

python createsuperuser
Superuser creation skipped due to not running in a TTY. You can run ` createsuperuser` in your project to create one manually.

I later checked that it was because git was being used to execute commands, and switching to the command line that comes with Windows solved the problem!

This is the whole content of this article, I hope it will help you to learn more.