Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 72

Connecting Django to PostgreSQL

Recommended resources

Hello and welcome back to the course!

In our last lesson, you did the foundational work on the database server itself: you created a dedicated database (myproject_db) and a user role (myproject_user) with a secure password. Your PostgreSQL server is now ready and waiting for your application.

Today, we will bridge the gap between your Django project and the database. The goal for this lesson is to configure your Django project's settings to connect to the PostgreSQL database. This is a critical step in moving from a simple development setup (using a single file for a database) to a professional, production-ready architecture.

1. The Python-PostgreSQL Bridge: The Database Adapter

Your Django application doesn't natively know how to speak the PostgreSQL "language." It needs a translator. In the Python world, this translator is a library called a database adapter. For PostgreSQL, the most widely used and recommended adapter is psycopg2.

Our first step is to install this adapter into your project's Python virtual environment.

The video below gives a quick demonstration of this process.

Django PostgreSQL | Django PostgreSQL Database Setup

This clip from Very Academy shows how to install the psycopg2 adapter using pip. This is the essential first step before Django can even attempt to connect to PostgreSQL.

Watch from 00:34 to 01:10. The key takeaway is the pip install command for the database driver.


2. Your Turn: Configuring the Connection

Now for the main event. You'll be editing your project's settings.py file to tell Django about the database you created in the last lesson. While you could write the username, password, and database name directly into the file, this is a major security risk. A much better practice, and the one we'll use, is to store these secrets in a separate file and have Django load them at runtime.

The following guide walks you through this professional approach.

Building CRUD Applications with Django and PostgreSQL

This article from BetterStack provides a clear, step-by-step guide on setting up a Django project to connect to PostgreSQL. It demonstrates the best practice of using a .env file and the python-decouple library to manage your database credentials securely.

Please read and follow the instructions in the section titled "Step 4 — Setting up your Django project". This section covers: Installing Django and psycopg2-binary. Installing python-decouple. Creating a .env file to store your database credentials. Modifying settings.py to securely load these credentials. Use the database name (myproject_db), username (myproject_user), and password you created in the previous lesson.

Let's break down the DATABASES dictionary you just configured in your settings.py:

  • 'ENGINE': This tells Django which database backend to use. django.db.backends.postgresql corresponds to the psycopg2 adapter you installed.
  • 'NAME': The name of the database you want to connect to (myproject_db).
  • 'USER': The PostgreSQL role Django should use to log in (myproject_user).
  • 'PASSWORD': The password for that user role.
  • 'HOST': The server where the database is running. Since it's on the same machine, localhost is correct.
  • 'PORT': The network port PostgreSQL is listening on. The default is 5432.

By using python-decouple, you keep all this sensitive information out of your main codebase. The .env file should never be committed to a version control system like Git.


3. Verification: Running Migrations

You've told Django how to connect. Now, let's confirm it works. The definitive test is to run Django's migrate command. This command instructs Django to connect to the database and create the initial tables it needs for features like user authentication, sessions, and the admin interface.

If the connection settings are correct, the command will succeed. If there's any issue (wrong password, incorrect database name, firewall blocking the port), it will fail here.

Your Turn:

  1. Make sure you are in your project directory (the one containing manage.py) and your virtual environment is activated.

  2. Run the migrate command:

    python manage.py migrate
    

You should see a series of "OK" messages as Django applies each migration.

To be absolutely sure, you can connect to psql and inspect the database directly.

  1. Open a new terminal.

  2. Connect to your project's database as its owner:

    psql -U myproject_user -d myproject_db
    
  3. When prompted for the password, enter the one you set for myproject_user.

  4. At the myproject_db=> prompt, list the tables with the \dt command:

    \dt
    

You should now see a list of tables like auth_user, django_session, etc. These are the tables Django just created, confirming your connection is working perfectly!

The following video shows this verification process, both the migrate command and checking the database afterward.

How to connect postgresql with django project ? | DRF

This clip from Codemiax demonstrates the final steps: running migrations and checking the database to confirm a successful connection.

Watch from 05:02 to 05:54. This will show you the expected output from the python manage.py migrate command and how the new tables appear inside the PostgreSQL database.


4. An Alternative: PostgreSQL Service Files

The .env file method is excellent and very common in the web development world. For completeness, it's good to know that PostgreSQL offers its own native way to manage connection parameters using service files.

PostgreSQL Connection Settings in Django
This image illustrates an alternative method where Django's `settings.py` points to a service name (`my_service`) defined in a separate `.pg_service.conf` file. The password can also be stored in a `.my_pgpass` file. This approach is often used by database administrators to centralize connection definitions.

This method is powerful because you can define a service once and have multiple applications and scripts refer to it by a simple name, without needing to know the host, port, or database name. You don't need to implement this now, but it's a valuable technique to be aware of, especially if you work in an environment with a dedicated database administration team.


Conclusion

Congratulations! You have successfully connected your Django application to a robust, production-grade PostgreSQL database. You've configured the connection using a secure and professional method, and verified that everything works as expected.

Key Takeaways:

  • Django requires a database adapter (like psycopg2) to communicate with a specific database system.
  • The DATABASES dictionary in settings.py is the control center for your application's database connection.
  • Never hardcode credentials in your source code. Using a .env file with a library like python-decouple is a standard, secure practice.
  • The python manage.py migrate command is the ultimate test of your database connection configuration.

Preview of the Next Lesson:
Your application can now talk to the database. But who else can? Right now, your PostgreSQL server is likely only accepting connections from localhost. The next step in hardening our setup is to configure PostgreSQL's host-based authentication rules. In the next lesson, we will dive into the pg_hba.conf file to precisely control which users can connect from which network addresses, adding another critical layer of security to your deployment.