Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Database configuration

How to Use PostgreSQL with Your Django Application

By Freedom251 Team · · 12 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To use PostgreSQL with Django, install a supported PostgreSQL server and the psycopg adapter, create an application database and least-privilege role, point DATABASES['default'] at the PostgreSQL backend, then run Django’s migrations. For Django 6.1, PostgreSQL 15 or newer and either psycopg 3.1.12 or newer (recommended) or psycopg2 2.9.9 or newer are required.

What Django–PostgreSQL compatibility means

Django talks to PostgreSQL through a Python database adapter. Your project therefore has three compatibility layers: the Django release, the PostgreSQL server, and the adapter installed in the same Python environment as Django.

As an Amazon Associate I earn from qualifying purchases.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Django 6.1 supports PostgreSQL 15 and higher. Its documented adapter requirements are psycopg 3.1.12 or later, or psycopg2 2.9.9 or later. Psycopg 3 is the preferred choice for a new project; psycopg2 remains supported for this release but is expected to be deprecated in the future. Older Django releases have different minimum PostgreSQL versions, so check the documentation for the exact Django version before upgrading either component.

A working connection is not enough by itself. The PostgreSQL role must be able to connect to the intended database and create or alter the objects your migrations require. In production, credentials, network access, connection limits, backups, and transaction behavior all matter as much as the ENGINE setting.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Prepare the database and application role

Install PostgreSQL using the package supplied for your operating system or use a PostgreSQL service that provides a host, port, database name, role, and password. Keep the application role separate from the PostgreSQL administrative role. The application normally needs ownership or appropriate privileges on its own database, not unrestricted access to every database on the server.

Create a database and role on a local server

The following example uses the PostgreSQL command-line client from a system account that is allowed to administer PostgreSQL. Replace the names and password with values for your project.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
sudo -u postgres psql
CREATE ROLE myapp_user WITH LOGIN PASSWORD 'replace-this-password';
CREATE DATABASE myapp OWNER myapp_user;
c myapp
GRANT CONNECT ON DATABASE myapp TO myapp_user;
q

Giving the role ownership of its application database is a simple local-development arrangement. In a more controlled deployment, an administrator can own the schema and grant only the specific rights required for migrations and runtime queries. Do not commit the password to Git, paste it into a public issue, or put it in a checked-in settings file.

Check the server endpoint

Record the values Django will need:

  • Database name: myapp in the example.
  • Role: myapp_user.
  • Host: 127.0.0.1 for a local TCP connection, or the private hostname supplied by your hosting environment.
  • Port: normally 5432, unless PostgreSQL was configured otherwise.
  • Password: supplied through an environment variable, secret manager, or PostgreSQL password file.

A local Unix-socket connection can behave differently from a TCP connection because PostgreSQL host-based authentication rules may select a different authentication method. Using an explicit host such as 127.0.0.1 makes the connection path clear and exposes port or firewall mistakes early.

Install the PostgreSQL adapter in Django’s environment

Activate the virtual environment used to run manage.py, then install psycopg 3:

python -m pip install 'psycopg[binary]'

The binary extra is convenient for development because it supplies the client components needed by the adapter. For a deployment that standardizes on system PostgreSQL libraries, install the plain psycopg package and follow your platform’s build requirements instead. The important point is that the package must be installed in the same interpreter environment as Django.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If your project must use psycopg2, install a version supported by your Django release:

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.
python -m pip install 'psycopg2>=2.9.9'

Confirm which interpreter and adapter are being used:

python -c "import sys, django, psycopg; print(sys.executable); print(django.get_version()); print(psycopg.__version__)"

If the command fails with ModuleNotFoundError, the usual cause is that pip installed the package into a different virtual environment. Always prefer python -m pip with the interpreter that launches Django.

Configure DATABASES safely

Django’s PostgreSQL backend is django.db.backends.postgresql. Put environment-specific values in environment variables rather than hard-coding credentials.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import os

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': os.environ.get('DB_HOST', '127.0.0.1'),
        'PORT': os.environ.get('DB_PORT', '5432'),
    }
}

For local development, define the variables in the shell that starts Django:

export DB_NAME=myapp
export DB_USER=myapp_user
export DB_PASSWORD='use-a-local-secret'
export DB_HOST=127.0.0.1
export DB_PORT=5432
python manage.py check

Use your deployment platform’s secret store or injected environment for production. Do not assume that an empty HOST is equivalent to 127.0.0.1; an empty value can make the PostgreSQL client choose a Unix socket, which changes authentication and connectivity behavior.

Use a PostgreSQL service or password file when appropriate

PostgreSQL supports service definitions and password files for deployments that centralize connection details. Django exposes those client options through the database configuration’s OPTIONS dictionary. A service-based configuration can keep the endpoint and TLS or authentication details out of application code, while a password file can keep the secret separate from the service definition. Ensure the password file has permissions restrictive enough for the operating system user running Django.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'OPTIONS': {
            'service': os.environ.get('PGSERVICE', 'myapp'),
            'passfile': os.environ.get('PGPASSFILE'),
        },
    }
}

Do not combine partially conflicting sources without understanding precedence. Choose one authoritative source for the host, database, role, and authentication settings and test it with the same operating-system user that runs the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Run migrations after connecting

Django migrations describe schema changes in Python and apply them to the configured database. PostgreSQL supports transactional DDL for many operations, so a failed migration can often roll back as a unit; individual operations and extensions can still have database-specific behavior.

Apply the project’s migration plan

  1. Check that Django can load the settings and reach the database:
    python manage.py check
  2. Create migration files for model changes:
    python manage.py makemigrations
  3. Apply all unapplied migrations:
    python manage.py migrate
  4. Inspect the state recorded for each app:
    python manage.py showmigrations
  5. Start the application and exercise at least one read and one write path. A successful migration does not prove that every query, constraint, index, or transaction path works.

Run makemigrations when models change, not merely every time the server starts. Commit migration files with the code that requires them, and run migrate as a deployment step against the intended database.

Switching an existing project from SQLite

Changing the backend changes the database, not just a setting. New PostgreSQL databases start without the rows stored in your SQLite file. Plan the data move separately from the schema move:

  1. Back up the SQLite database and record the current migration state.
  2. Configure PostgreSQL and run the project migrations to create a clean schema.
  3. Export application data using a method appropriate to your models and relationships, then import it into PostgreSQL.
  4. Validate row counts, uniqueness constraints, timestamps, files, and any database-specific fields.
  5. Run the application against PostgreSQL in a staging environment before changing production traffic.

Do not treat a successful migrate as a data migration. Fixtures, custom scripts, or a database-level transfer may be needed, especially when SQLite’s permissive typing differs from PostgreSQL’s constraints.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the connection from Django and PostgreSQL

When a connection fails, identify which layer failed instead of changing several settings at once.

  • Adapter layer: Python can import psycopg from the active environment.
  • Network layer: the configured host resolves, PostgreSQL is listening on the configured port, and firewall or private-network rules allow the connection.
  • Authentication layer: the role exists, the password is current, and PostgreSQL host-based authentication rules allow the client address and method.
  • Authorization layer: the role can connect to the database and perform the DDL or queries required by the application.
  • Migration layer: the migration graph is consistent and required extensions or dependencies exist.

Use the PostgreSQL client with the same values as Django to isolate application settings from server behavior:

psql --host=127.0.0.1 --port=5432 --username=myapp_user --dbname=myapp

Once connected, conninfo shows the endpoint and role used by the client. Never include a password in a shell command that may be saved in shell history; let psql prompt for it or use a protected password file.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Use PostgreSQL-specific Django features deliberately

Django includes PostgreSQL-specific fields and migration operations through its PostgreSQL integration. These features can improve querying and data modeling, but they reduce portability to other database engines.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Enable an extension such as hstore

An extension must exist in the target database before code that depends on it can work. Django provides an extension migration operation, but the database role running migrations may not have permission to create extensions. If it lacks that privilege, an administrator must create the extension outside the migration process.

from django.contrib.postgres.operations import HStoreExtension
from django.db import migrations

class Migration(migrations.Migration):
    operations = [
        HStoreExtension(),
    ]

Coordinate extension creation with the person or service managing PostgreSQL. Test the migration on a fresh database and on an existing database so that deployment order is explicit. Similar considerations apply to other PostgreSQL extensions: availability depends on the server build and the privileges granted to your role.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose production connection behavior

The simplest production configuration uses short-lived connections and PostgreSQL’s default transaction isolation. Change those defaults only when you can explain the workload benefit and have a plan for limits, retries, and monitoring.

Transaction isolation

Django uses PostgreSQL’s READ COMMITTED isolation level by default. It allows each statement to see data committed before that statement begins and is a practical default for most web applications.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

REPEATABLE READ and SERIALIZABLE provide stronger consistency guarantees but can cause serialization failures when concurrent transactions conflict. If you select a higher level through the connection options, catch the database exception at an appropriate transaction boundary and retry only operations that are safe to repeat. Retrying an operation with external side effects requires an idempotency design, not a blind loop.

Persistent connections with CONN_MAX_AGE

Django controls persistent connections with CONN_MAX_AGE. A value of 0 closes the connection at the end of each request, while a positive value keeps it available for that many seconds and None allows it to remain open indefinitely, subject to health checks and server behavior.

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': os.environ['DB_HOST'],
        'PORT': os.environ.get('DB_PORT', '5432'),
        'CONN_MAX_AGE': int(os.environ.get('DB_CONN_MAX_AGE', '60')),
    }
}

Persistent connections reduce connection setup overhead, but every worker, thread, process, or asynchronous execution unit can consume a connection. Compare the maximum possible application connections with PostgreSQL’s connection limit and with connections reserved for administration, background jobs, monitoring, and migrations. A value that works for one development process can exhaust a production database when multiplied across several workers.

Psycopg connection pooling

Django supports psycopg connection pooling through the OPTIONS pool setting. When pooling is enabled, Django’s CONN_MAX_AGE must be 0; the pool, not Django’s persistent-connection setting, owns connection lifetime.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': os.environ['DB_NAME'],
        'USER': os.environ['DB_USER'],
        'PASSWORD': os.environ['DB_PASSWORD'],
        'HOST': os.environ['DB_HOST'],
        'PORT': os.environ.get('DB_PORT', '5432'),
        'CONN_MAX_AGE': 0,
        'OPTIONS': {
            'pool': {
                'min_size': 1,
                'max_size': 10,
                'timeout': 30,
            },
        },
    }
}

Treat the pool limits in this example as configuration examples, not universal recommendations. Size the pool against the number of application instances and the database’s connection capacity. Monitor wait time, pool exhaustion, database connections, and error rates before increasing limits.

Server-side parameter binding

Psycopg 3.1.8 and later can use server-side parameter binding when enabled in Django’s OPTIONS. The setting is ignored when the project uses psycopg2. Enable it only after testing raw SQL and third-party packages that may depend on client-side adaptation or particular parameter behavior.

Compare local, self-managed, and managed PostgreSQL

The Django configuration is similar in all three cases; the operational responsibilities are not.

Decision axis Local PostgreSQL Self-managed production PostgreSQL Managed PostgreSQL
Operational ownership You install, upgrade, secure, and repair the server on your workstation or development host. Your team owns operating-system maintenance, PostgreSQL upgrades, failover, and incident response. The service operator usually handles much of the infrastructure work; you still own application configuration, access policy, and service-level decisions.
Backup and restore Backups are usually manual and are often omitted unless you create a routine. You design, test, encrypt, and monitor backups and point-in-time recovery. Backup features may be supplied, but retention, restore testing, export access, and recovery objectives must be verified.
Network latency and private connectivity Loopback connections are fast and simple. You design routing, TLS, firewall rules, and private access between application and database hosts. Private networking, allowed-source rules, regions, and cross-zone latency depend on the service and must be checked before deployment.
Connection limits and pooling Limits are easy to overlook because only a few processes connect. You size PostgreSQL and any pooler against every worker and background process. The service plan may impose connection limits; pooling and instance count still need application-side planning.
Extension availability You can generally install extensions supported by the local server package. You control the server build and extension lifecycle. Only the extensions and versions exposed by the service are available, and privileged creation may be restricted.
Scaling controls Scaling means changing the local machine or moving the database. You choose vertical scaling, replicas, storage, and failover architecture. Scaling controls, maintenance windows, replicas, and storage options are determined by the service’s offerings.
Observability Use local logs and PostgreSQL inspection tools. You configure metrics, logs, alerts, and query analysis. Built-in metrics can help, but confirm retention, granularity, export, and alerting capabilities.
Cost and compliance Uses existing hardware but consumes local resources. Includes infrastructure, operations, staffing, and recovery costs. Billing, data location, support, encryption, audit controls, and compliance attestations vary by service and region.

Verify provider-specific connection limits, extension lists, backup guarantees, private-network features, regions, and compliance terms directly with the service you are considering. Django’s pooling and connection settings do not override those external limits.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot the failures you are most likely to see

ModuleNotFoundError: psycopg

  • Activate the virtual environment used by manage.py.
  • Run python -m pip install 'psycopg[binary]' with that interpreter.
  • Check the Django version and install an adapter version in its supported range.
  • Confirm the import with python -c "import psycopg; print(psycopg.__version__)".

Authentication failure

Check NAME, USER, PASSWORD, HOST, and PORT as one set. Then verify that the PostgreSQL role exists, has LOGIN, has access to the database, and is allowed by the server’s host-based authentication rules. A password that works through a local socket may fail over TCP because a different rule applies.

Connection refused or timeout

Confirm that PostgreSQL is running and listening on the configured address and port. Check local firewall rules, container or virtual-machine port forwarding, cloud security rules, private-network routes, and whether the hostname resolves to the expected network. A refusal usually means no process is accepting the connection; a timeout often indicates filtering or an unreachable route.

Migration errors

Run showmigrations and inspect the first failing migration, its dependencies, and the database role’s DDL privileges. If a field or operation requires an extension, verify that the extension exists in the same database and schema. An administrator may need to create it before the migration can complete. Do not repeatedly delete migration files on a shared database; reconcile the migration history and schema deliberately.

Unexpected serialization failures

These are expected possibilities when using REPEATABLE READ or SERIALIZABLE. Keep transactions short, identify the conflicting operation, and add bounded retry handling around an idempotent transaction. If the application does not need the stronger guarantee, return to the default isolation level rather than hiding conflicts with unlimited retries.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Production readiness checklist

  • Use a Django release and PostgreSQL version with a documented compatibility range.
  • Pin the psycopg major version and test upgrades in staging.
  • Use a dedicated role, a strong secret outside source control, and the narrowest practical privileges.
  • Restrict database network access to application and administration paths.
  • Run migrations as a controlled deployment step and record their outcome.
  • Test backups by restoring them, not merely by checking that a backup job ran.
  • Set connection lifetime or pool limits after counting every application worker and background process.
  • Monitor connection utilization, query latency, locks, failed transactions, storage, and replication or failover health where applicable.
  • Document extension ownership and the administrator procedure for creating extensions.
  • Exercise a read, write, rollback, timeout, and recovery path in staging before production traffic is enabled.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Database configurationDjangoPostgreSQLPsycopgPythonWeb development

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.