Introduction
In this article, the main content will be just how to define a database configuration in Django application. Normally, there is a file which is responsible for the database configuration in Django application. That file exist in the project folder with the name of ‘settings.py’. This file is responsible for almost Django application setting configuration. But before going on further, just check several articles about Django application. One of the article is about How to Create Django Project in Microsoft Windows using Command Line for creating a Django project. Another one is about How to Create a Django Application inside a Django Project in Microsoft Windows which is for create a Django application inside the Django project.
How to Define Database Configuration in Django Application
Actually, inside the Django project, there is a file with the name of ‘settings.py’. Normally, it exist in the following structure :
C:\django\myproject>tree Folder PATH listing for volume Windows-SSD Volume serial number is CA30-19A4 C:. ├───myapp │ ├───migrations │ │ └───__pycache__ │ ├───templates │ │ └───myapp │ └───__pycache__ └───myproject └───__pycache__ C:\django\myproject>
That file exist in the ‘myproject’ folder which is the folder of the Django project.
C:\django\myproject\myproject>tree /F . Folder PATH listing for volume Windows-SSD Volume serial number is CA30-19A4 C:\DJANGO\MYPROJECT\MYPROJECT │ asgi.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ └───__pycache__ settings.cpython-310.pyc urls.cpython-310.pyc wsgi.cpython-310.pyc __init__.cpython-310.pyc C:\django\myproject\myproject>
As it exists in the above output command of ‘tree /F .’, there is a file with the name of ‘settings.py’. Open it and add the database setting configuration as follows :
# Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } }
By default, the above section is the default configuration for database connection. In order to add a new one, just comment the ‘default’ one or just add another one. In this context, the step is just to comment the default database connection and add a new one. That new one basically replacing the old one as in the following revision :
# Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': BASE_DIR / 'db.sqlite3', # }, 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'django_training', 'USER': 'postgres', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432' } }