Configuring a Django Project to Use PostgreSQL

Django projects are configured by default to use a SQLite database, but the framework has built-in support for PostgreSQL as well, which is more suitable for production. If you haven't created your first Django project yet, see Creating and Setting Up a Django Project. Here's how to set up things to run your Django application with a PostgreSQL database.

First, make sure you have a PostgreSQL server running. The most quickly way to do this is via Docker. This command will launch a new container with a fresh PostgreSQL database:

docker run -p 5432:5432 --name oscardb -e POSTGRES_PASSWORD=postgres -d postgres

Once Postgres is running, you also need to install the third-party Python package which Django will use under the hood to communicate with your database. The recommended package is Psycopg. You can install it by running:

pip install "psycopg[binary]"

Now go to your project's settings.py and replace the default DATABASES dictionary with the following:

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": "postgres",
        "USER": "postgres",
        "PASSWORD": "postgres",
        "HOST": "127.0.0.1",
        "PORT": "5432",
    }
}

Since this will make your Django application use a new database, make sure to run migrations, even if you haven't created any models yet:

python manage.py migrate

If this command runs without any errors, congratulations! Your Django application is now working with a PostgreSQL database.