How to Connect a Django App to a Database

Database management with Django

Sjlouji
Python in Plain English

--

Django officially supports five databases.

  1. PostgreSQL
  2. MariaDB
  3. MySQL
  4. Oracle
  5. SQLite
Databases used with Django
Databases used with Django

In this blog, I am explaining how to connect Django with PostgreSQL, Mysql, and SQLite the database. I have already created a helloworld Django project. If you need assistance for creating a basic Django app, have a look at my previous blog( Hello World app with Django ).

SQLite

SQLite is an open-source database that helps to interact with relational databases. SQLite is stored as a single file. This makes sharing databases easier. By default, Django uses the SQLite database.

  1. To connect with the SQLite database, make sure you have db.sqlite3 file in the home directory.
Project Structure of My Django Application
Project Structure of My Django Application

2. Now open the helloworld/settings.py file. Scroll down to the database section. You might see something like this. This is where we initialize all the database credentials. If you don’t see something like this, then manually add the below code under the database section.

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

3. Now you are good to go.

(hello-world-django) bash-3.2$ python3 manage.py migrate

With the command, all the migrations will be applied and you can start building your application.

Migration
Migration

4. To verify if the databases have been created. Just use the below command

(hello-world-django) bash-3.2$ sqlite3  db.sqlite3SQLite version 3.28.0 2019-04-15 14:49:49Enter ".help" for usage hints.sqlite> 

Now just type .tables to view all the tables created.

sqlite> .tablesauth_group                  auth_user_user_permissionsauth_group_permissions      django_admin_logauth_permission             django_content_typeauth_user                   django_migrationsauth_user_groups            django_session

PostgreSQL

PostgreSQL is an open-source Relational Database Management System that is used for its high level of resilience, integrity, and correctness. PostgreSQL is used as a database warehouse for many mobile and web applications. It is also used with many analytical applications. PostgreSQL is a perfect match for Data science. It provides good support and agility to work with Big Data. To work with PostgreSQL, you should have any of the PostgreSQL clients. I am using pgAdmin.

  1. Create a new Database in pgAdmin.
Creating a new Database
Creating a new Database
CURD-Django
Database Schema — CURD-Django

2. Connecting our helloworld Django project with our PostgreSQL.

Install psycopg2. Psycopg2 is a database adapter commonly used for python programming language.

(hello-world-django) bash-3.2$ pip install psycopg2

Now open the helloworld/settings.py file. Scroll to the database section. There you should see the below code.

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

Now just replace the above code with our connection credentials for pgAdmin. The updated code should look like the code below.

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'CURD-Django', #Database Name
'USER': 'postgres', #Your Postgresql user
'PASSWORD': 'admin', #Your Postgresql password
'HOST': '127.0.0.1',
'PORT': '5432',
}
}

3. Migrate your project. By default, Django provides some migrations.

(hello-world-django) bash-3.2$ python3 manage.py migrateOperations to perform:Apply all migrations: admin, auth, contenttypes, sessionsRunning migrations:Applying contenttypes.0001_initial... OKApplying auth.0001_initial... OKApplying admin.0001_initial... OKApplying admin.0002_logentry_remove_auto_add... OKApplying admin.0003_logentry_add_action_flag_choices... OKApplying contenttypes.0002_remove_content_type_name... OKApplying auth.0002_alter_permission_name_max_length... OKApplying auth.0003_alter_user_email_max_length... OKApplying auth.0004_alter_user_username_opts... OKApplying auth.0005_alter_user_last_login_null... OKApplying auth.0006_require_contenttypes_0002... OKApplying auth.0007_alter_validators_add_error_messages... OKApplying auth.0008_alter_user_username_max_length... OKApplying auth.0009_alter_user_last_name_max_length... OKApplying auth.0010_alter_group_name_max_length... OKApplying auth.0011_update_proxy_permissions... OKApplying auth.0012_alter_user_first_name_max_length... OKApplying sessions.0001_initial... OK
Database Schema
Database Schema

After successful migration, you should see a database schema like this.

MySql

Mysql database is also a widely used database among the industry. Mysql is also a Relational Database Management System. Mysql SQL is used widely with e-commerce, data warehousing, and logging applications. Mysql is a web database. Creating a database with Mysql in Django is similar to what we did for PostgreSQL. Here I am using PhpMyAdmin which is a Mysql client.

1. Create a new Database in PhpMyAdmin

CURD-DJANGO database in PhpMyAdmin
CURD-DJANGO database in PhpMyAdmin

2. Connecting our helloworld Django project with our Mysql client

Now open the helloworld/settings.py file. Scroll to the database section. There you should see the below code.

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}

Now we should replace the above code with our connection credentials to Mysql. The updated code should look like the code below.

# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #Mysql Client Adapter
'NAME': 'CURD-django', #Database Name
'USER': 'root', #Your Postgresql user
'PASSWORD': 'root', #Your Postgresql password
'HOST': '127.0.0.1',
'PORT': '3306',
}
}

3. Install Mysql Client

We initialized the adapter settings. But not yet downloaded. Download the MySQL client with the command.

(hello-world-django) bash-3.2$ pip install mysqlclient

After installation, open the file helloworld/__init__.py and add the below code in it.

import pymysql
pymysql.install_as_MySQLdb()

4. Migrate your project

(hello-world-django) bash-3.2$ python3 manage.py migrateOperations to perform:Apply all migrations: admin, auth, contenttypes, sessionsRunning migrations:Applying contenttypes.0001_initial... OKApplying auth.0001_initial... OKApplying admin.0001_initial... OKApplying admin.0002_logentry_remove_auto_add... OKApplying admin.0003_logentry_add_action_flag_choices... OKApplying contenttypes.0002_remove_content_type_name... OKApplying auth.0002_alter_permission_name_max_length... OKApplying auth.0003_alter_user_email_max_length... OKApplying auth.0004_alter_user_username_opts... OKApplying auth.0005_alter_user_last_login_null... OKApplying auth.0006_require_contenttypes_0002... OKApplying auth.0007_alter_validators_add_error_messages... OKApplying auth.0008_alter_user_username_max_length... OKApplying auth.0009_alter_user_last_name_max_length... OKApplying auth.0010_alter_group_name_max_length... OKApplying auth.0011_update_proxy_permissions... OKApplying auth.0012_alter_user_first_name_max_length... OKApplying sessions.0001_initial... OK

Now you should see the default database schema in PhpMyAdmin.

Happy coding!

--

--

Software Engineer at @Pando. Developer | Writer. From ABC to the world of code.