Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      CodeSOD: Pretty Little State Machine

      September 9, 2025

      The Value-Driven AI Roadmap

      September 9, 2025

      This week in AI updates: Mistral’s new Le Chat features, ChatGPT updates, and more (September 5, 2025)

      September 6, 2025

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Development Release: KDE Linux 20250906

      September 6, 2025

      Hitachi Energy Pledges $1B to Strengthen US Grid, Build Largest Transformer Plant in Virginia

      September 5, 2025

      How to debug a web app with Playwright MCP and GitHub Copilot

      September 5, 2025

      Between Strategy and Story: Thierry Chopain’s Creative Path

      September 5, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Finally, safe array methods in JavaScript

      September 9, 2025
      Recent

      Finally, safe array methods in JavaScript

      September 9, 2025

      Perficient Interviewed for Forrester Report on AI’s Transformative Role in DXPs

      September 9, 2025

      Perficient’s “What If? So What?” Podcast Wins Gold Stevie® Award for Technology Podcast

      September 9, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Speed Isn’t Everything When Buying SSDs – Here’s What Really Matters!

      September 8, 2025
      Recent

      Speed Isn’t Everything When Buying SSDs – Here’s What Really Matters!

      September 8, 2025

      14 Themes for Beautifying Your Ghostty Terminal

      September 8, 2025

      Development Release: KDE Linux 20250906

      September 6, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Use PostgreSQL in Django

    How to Use PostgreSQL in Django

    April 22, 2025

    If you’re building a Django project and wondering which database to use, PostgreSQL is a great choice. It’s reliable, fast, packed with powerful features, and works beautifully with Django.

    I’ve used it across multiple projects – from small web apps to large-scale platforms – and it never disappoints.

    In this post, I’ll walk you through how to connect PostgreSQL with Django step-by-step.

    Let’s get started.

    What we’ll cover:

    1. Why Use PostgreSQL with Django?

    2. What You’ll Need

    3. How to Use PostgreSQL in Django

      • Step 1: Install PostgreSQL

      • Step 2: Install the PostgreSQL Adapter for Python

      • Step 3: Create a Django Project (If You Haven’t Yet)

      • Step 4: Create a PostgreSQL Database

      • Step 5: Update Django Settings to Use PostgreSQL

      • Step 6: Run Migrations

      • Step 7: Test the Connection

    4. Common Issues (and Fixes)

    5. Optional: Use dj-database-url for Better Settings

    6. Frequently Asked Questions

      • Is PostgreSQL better than SQLite for Django?

      • Do I need to install PostgreSQL on my production server?

      • Is psycopg2-binary safe to use in production?

      • Can I switch from SQLite to PostgreSQL mid-project?

    7. Wrapping Up

    8. Further Resources

    Why Use PostgreSQL with Django?

    PostgreSQL is a popular, open-source relational database that’s known for its performance, flexibility, and powerful features like:

    • Advanced data types (JSON, arrays, and so on)

    • Full-text search

    • Support for complex queries

    • Data integrity and reliability

    Django officially recommends PostgreSQL as the most feature-complete database backend it supports. If you’re planning to build a serious web application, PostgreSQL is usually the best database to pair with Django.

    What You’ll Need

    Before we begin, make sure you have the following:

    • Python installed (3.7 or higher is best)

    • Django installed (I’ll be using version 4.x)

    • PostgreSQL installed and running

    • psycopg2 or psycopg2-binary (This is the adapter that lets Django talk to PostgreSQL)

    How to Use PostgreSQL in Django

    Here is how to get started:

    Step 1: Install PostgreSQL

    If you haven’t installed PostgreSQL yet, you can grab it from the official PostgreSQL website. It works on Windows, macOS, and Linux.

    Make sure you remember the username, password, and database name when you set it up – you’ll need those later.

    Step 2: Install the PostgreSQL Adapter for Python

    Django needs a little help to connect with PostgreSQL. That’s where psycopg2 comes in.

    You can install it using pip:

    pip install psycopg2-binary
    

    Tip: The -binary version is easier to install and works for most people. If you run into issues later, you can switch to psycopg2 (non-binary).

    Step 3: Create a Django Project (If You Haven’t Yet)

    If you haven’t created a project yet, start with:

    django-admin startproject myproject
    <span class="hljs-built_in">cd</span> myproject
    

    This will give you the basic project structure.

    Step 4: Create a PostgreSQL Database

    Now, open your PostgreSQL client (like psql or pgAdmin), and create a new database:

    <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> mydatabase;
    <span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> myuser <span class="hljs-keyword">WITH</span> <span class="hljs-keyword">PASSWORD</span> <span class="hljs-string">'mypassword'</span>;
    <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> client_encoding <span class="hljs-keyword">TO</span> <span class="hljs-string">'utf8'</span>;
    <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> default_transaction_isolation <span class="hljs-keyword">TO</span> <span class="hljs-string">'read committed'</span>;
    <span class="hljs-keyword">ALTER</span> <span class="hljs-keyword">ROLE</span> myuser <span class="hljs-keyword">SET</span> timezone <span class="hljs-keyword">TO</span> <span class="hljs-string">'UTC'</span>;
    <span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">PRIVILEGES</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">DATABASE</span> mydatabase <span class="hljs-keyword">TO</span> myuser;
    

    This sets up a database and user with the right permissions. Replace mydatabase, myuser, and mypassword with whatever values you prefer.

    Step 5: Update Django Settings to Use PostgreSQL

    Now it’s time to tell Django to use your new PostgreSQL database.

    Open myproject/settings.py and look for the DATABASES setting. Replace the default sqlite3 section with this:

    DATABASES = {
        <span class="hljs-string">'default'</span>: {
            <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.postgresql'</span>,
            <span class="hljs-string">'NAME'</span>: <span class="hljs-string">'mydatabase'</span>,
            <span class="hljs-string">'USER'</span>: <span class="hljs-string">'myuser'</span>,
            <span class="hljs-string">'PASSWORD'</span>: <span class="hljs-string">'mypassword'</span>,
            <span class="hljs-string">'HOST'</span>: <span class="hljs-string">'localhost'</span>,
            <span class="hljs-string">'PORT'</span>: <span class="hljs-string">'5432'</span>,
        }
    }
    

    This tells Django to:

    • Use PostgreSQL (django.db.backends.postgresql)

    • Connect to a local database called mydatabase

    • Use the user and password you set up earlier

    Step 6: Run Migrations

    Now that everything’s connected, let’s create the database tables Django needs:

    python manage.py migrate
    

    If everything’s working, you’ll see Django creating tables in PostgreSQL. No errors? You’re good to go!

    Step 7: Test the Connection

    Let’s test it all by creating a superuser (admin account):

    python manage.py createsuperuser
    

    Follow the prompts, then run:

    python manage.py runserver
    

    Open your browser and go to http://127.0.0.1:8000/admin. Log in with your superuser account. You’ll be in the Django admin dashboard – and yes, all of this is backed by PostgreSQL now!

    Common Issues (and Fixes)

    Here are a few things that might trip you up:

    • Error: psycopg2.errors.UndefinedTable: This usually means you forgot to run migrate.

    • Can’t connect to database: Double-check your database name, user, and password. Make sure PostgreSQL is running.

    • Role doesn’t exist: You might’ve forgotten to create the user in PostgreSQL, or you used the wrong name in settings.py.

    Optional: Use dj-database-url for Better Settings

    If you’re planning to deploy your app later (especially on services like Heroku), managing your database settings through a URL is cleaner.

    Install the helper package:

    pip install dj-database-url
    

    Then in your settings.py:

    <span class="hljs-keyword">import</span> dj_database_url
    
    DATABASES = {
        <span class="hljs-string">'default'</span>: dj_database_url.config(default=<span class="hljs-string">'postgres://myuser:mypassword@localhost:5432/mydatabase'</span>)
    }
    

    This lets you control your database config from an environment variable, which is more secure and flexible.

    Frequently Asked Questions

    Is PostgreSQL better than SQLite for Django?

    For learning or small projects, SQLite is fine. But for serious apps with lots of users or advanced queries, PostgreSQL is much better.

    Do I need to install PostgreSQL on my production server?

    Yes – unless you’re using a hosted PostgreSQL solution like Amazon RDS, Heroku Postgres, or Supabase.

    Is psycopg2-binary safe to use in production?

    Yes, for most cases. But some recommend switching to the non-binary version (psycopg2) in production for better control.

    Can I switch from SQLite to PostgreSQL mid-project?

    Yes, but you’ll need to migrate your data. Tools like Django’s dumpdata and loaddata can help with that.

    Wrapping Up

    Using PostgreSQL in Django is a great step forward when you want to build real, production-ready apps.

    The setup is pretty straightforward once you know the steps, and the performance gains are worth it.

    Come say hey on X.com/_udemezue and check out my blog while you’re at it!

    Further Resources

    If you want to dive deeper, here are a few links I recommend:

    • Django Database Settings Docs

    • PostgreSQL Official Documentation

    • Using PostgreSQL with Django (Real Python)

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleHow to Use a Foreign Key in Django
    Next Article How to Write a Good Conference Talk Proposal – CFP Guide

    Related Posts

    Development

    Stop Duct-Taping AI Agents Together: Meet SmythOS

    September 9, 2025
    Development

    How to Get Started With Navigation in Flutter Using AutoRoute

    September 9, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-6300 – PHPGurukul Employee Record Management System SQL Injection Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2024-51553 – ASPECT Predictable Filename Information Disclosure Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    Your Android phone is getting a big security upgrade for free – here’s what’s new

    News & Updates

    BrowserStack launches Chrome extension that bundles 10+ manual web testing tools

    Tech & Work

    Highlights

    CVE-2025-4946 – Vikinger WordPress Theme Arbitrary File Deletion Vulnerability

    July 2, 2025

    CVE ID : CVE-2025-4946

    Published : July 2, 2025, 10:15 a.m. | 1 hour, 28 minutes ago

    Description : The Vikinger theme for WordPress is vulnerable to arbitrary file deletion due to insufficient file path validation in the vikinger_delete_activity_media_ajax() function in all versions up to, and including, 1.9.32. This makes it possible for authenticated attackers, with Subscriber-level access and above, to delete arbitrary files on the server, which can easily lead to remote code execution when the right file is deleted (such as wp-config.php). Note: Requires Vikinger Media plugin to be installed and active.

    Severity: 8.1 | HIGH

    Visit the link for more details, such as CVSS details, affected products, timeline, and more…

    Postgres RAG Stack: Embedding, Chunking & Vector Search

    July 17, 2025

    CVE-2025-4447 – Eclipse OpenJ9 OpenJDK Stack Buffer Overflow

    May 9, 2025

    CVE-2025-8168 – D-Link DIR-513 Buffer Overflow Vulnerability

    July 28, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.