In this article, you will learn how to connect to a postgreSQL database to a Python web application framework Django. You will also learn how to edit your Django Project Settings file and connect your web application to a PostgreSQL Database.
After walking through the Django installation process it shows how to get started creating a simple Django application.
Connecting your Django App to a PostgreSQL Database
# Introduction:
Django is a flexible framework for quickly creating Python applications. By default, Django applications are configured to store data into a lightweight SQLite database file. While this works well under some loads, a more traditional DBMS can improve performance in production.
Let's see, How to use a postgres database in Django app :
Step 1 : When you open the pgadmin panel you will view a server icon in the navigation at the left side of the window. Click on it to open the databases icon. Right Click on the databases icon to create a new database and fill the prerequisites for creating the database.
Step 2 : Next we need to install an adapter for connecting our database with the Django App. We will be using "psycopg2" for this purpose.
pip install psycopg2
Step 3 : Now go-to the "settings.py" file of the Django App and Under the settings file for Databases, change the settings from sqlite3 or your current database to the following code.
➤ Code: settings.py (sqlite3)
DATABASES={
'default':{
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
➤ Code: settings.py (postgresql)
DATABASES={
'default':{
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'your-db-name',
'USER': 'user_name',
'PASSWORD': 'your-db-password',
'HOST': 'localhost',
'PORT': '5432',
}
}
Step 4 : Now run makemigrations command to convert all the models into queries for the database.
pip manage.py makemigrations
Step 5 : And finally run migrate command to migrate these changes into our database.
pip manage.py migrate
Servers>PostgreSQL>Databases>DB_Name>Schema>Public>Tables
You can go to the pgAdmin panel to check the changes on the database that you have just made in the form of tables that are visible in the following column.
Note that: To install psycopg2 adapter, We will also need to install pillow in case we wish to save any pictures in our database. This can be done using. Have fun!
pip install pillow
Comments