You are currently viewing How to Connect a Django Application to PostgreSQL

How to Connect a Django Application to PostgreSQL

PostgreSQL is a powerful open-source relational database management system, while Django is a popular web framework for building web applications. In this blog article, we cover how to Connect a Django Application to PostgreSQL. The assumption is that you have an existing web application, ie, you have created a Django application, started a project and now wish to configure the database.

How to Connect a Django Application to PostgreSQL Database

Step 1: Install Django and PostgreSQL

First, make sure you have Django and psycopg2 installed in your Django project.

pip install django psycopg2-binary

Step 2: Configure Django Settings

Open your Django project’s settings file (settings.py) and configure the DATABASES setting to use PostgreSQL: The file settings.py is found under the Django project folder.

The default Database settings are as shown below.

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}

Replace the database code with the code below and update the fields as required.

# settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydatabase',       # Replace with your actual database name
        'USER': 'myuser',           # Replace with your actual database username
        'PASSWORD': 'mypassword',   # Replace with your actual database password
        'HOST': 'localhost',       # Replace with your actual database host 
        'PORT': '5432',             # Replace with your actual database port if different
    }
}

Replace mydatabase, myuser, mypassword, localhost, and 5432 with your actual PostgreSQL database details.

NOTE

  1. If the database is hosted on a different server from the application, enter the hostname or server IP in the HOST section.
  2. Ensure to create a database and a user with the same details that you enter in the settings.py database section.

Step 3: Migrate Database

Now, run the Django migrate command to create the necessary database schema in PostgreSQL:

python manage.py makemigrations
python manage.py migrate

In some cases, the migration may fail with the following errors excerpt.

 line 70, in ensure_schema
    raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc)
django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (permission denied for schema public
LINE 1: CREATE TABLE "django_migrations" ("id" bigserial NOT NULL PR...

To resolve such an error, run the following command:

GRANT postgres TO <myuser>;  #where myuser is the database user configured in django.

Upon a successful connection, Django will automatically migrate the defined database schema and create the corresponding tables in the PostgreSQL database.

Step 4: Run the Application

Start your Django application using the runserver command:

python manage.py runserver

Your Django application has now been successfully connected to PostgreSQL. Any models you define in your Django application will use this database for data storage.

Why use PostgreSQL as the database for a Django application?

  1. Reliability and Stability: PostgreSQL is known for its reliability and stability. It’s ACID-compliant (Atomicity, Consistency, Isolation, Durability), making it a good choice for applications where data integrity and consistency are critical.
  2. Scalability: PostgreSQL can handle large amounts of data and is highly scalable. It allows for efficient scaling of both read and write operations, making it suitable for applications with a growing user base.
  3. Advanced Features: PostgreSQL provides advanced features such as full-text search, JSON support, geospatial capabilities, and advanced indexing options. These features can be beneficial for a variety of applications, especially those dealing with complex data types.
  4. Open Source and Community-Driven: PostgreSQL is open-source, with an active and vibrant community. This means continuous improvements, updates, and a wealth of resources and community-contributed extensions to enhance its functionality.
  5. Cross-Platform Support: PostgreSQL runs on multiple platforms, including Linux, Windows, macOS, and others, providing flexibility in deployment.
  6. Data Integrity and Data Types: PostgreSQL supports a wide range of data types, including custom data types. It enforces data integrity through constraints, triggers, and foreign keys, ensuring the quality and consistency of the stored data.
  7. Security: PostgreSQL offers robust security features, including SSL certificates, data encryption, authentication, and role-based access control, helping to secure sensitive data.
  8. Performance Optimization: PostgreSQL allows for performance optimization through query optimization, indexing, and performance tuning, ensuring efficient database operations.
  9. Cost-Effectiveness: Being open-source, PostgreSQL is cost-effective in terms of licensing and operating costs compared to some commercial database systems.

Make a donation to support us



Web Hosting and email hosting Packages


Related Content