PostgreSQL setup with Django in Ubuntu 22.04

Table of contents

No heading

No headings in the article.

To link PostgreSQL to Django, you need to perform the following steps:

  1. Install Required Packages: Make sure you have the necessary packages installed to work with PostgreSQL in Django. You can install them using the following command:

     pip install psycopg2-binary
    
  2. Configure Database Settings: In your Django project, open the settings.py file and locate the DATABASES setting. Update it with the following configuration:

     DATABASES = {
         'default': {
             'ENGINE': 'django.db.backends.postgresql',
             'NAME': 'your_database_name',
             'USER': 'your_username',
             'PASSWORD': 'your_password',
             'HOST': 'localhost',
             'PORT': '5432',
         }
     }
    

    Replace 'your_database_name', 'your_username', and 'your_password' with your actual PostgreSQL database name, username, and password. If your PostgreSQL database is hosted on a different host or port, update the 'HOST' and 'PORT' values accordingly.

  3. Apply Database Migrations: Run the following command to apply the initial database migrations:

     python manage.py migrate
    

    This command will create the necessary tables in the PostgreSQL database for Django's default apps and any additional apps you may have added.

  4. Verify the Connection: You can verify the connection to the PostgreSQL database by running the following command:

     python manage.py check
    

    If the connection is successful, you should see a message indicating that the database connection is operational.

That's it! Your Django project is now linked to the PostgreSQL database. You can define models, create new migrations, and interact with the database using Django's ORM (Object-Relational Mapping).