"PostgreSQL 12 or later is required (found 10.23)" Django error while connecting to PostgreSQL 16

Exception Type: NotSupportedError

Exception Value: PostgreSQL 12 or later is required (found 10.23).

The above exception is thrown by the db backend. The obvious assumption would a mismatch of versions; it isn't the case as I have made certain of this. The connection is to a remote db running on v16. Indeed, I have even migrated services but to no avail just to make sure. Also, it a bit imprecise as I was able to migrate, createsuperuser and create some objects from admins before the error was thrown again.

settings/init.py:

import os

if os.environ.get("ENV_NAME") == 'production':
    from .production import *
elif os.environ.get("ENV_NAME") == 'staging':
    from .staging import *
else:
    from .base import *

settings/base.py (contains base settings)

import os
from pathlib import Path
import environ
import dj_database_url

env = environ.Env()

# Take environment variables from .env file
environ.Env.read_env()


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent.parent # add ".parent" after creating new folder for settings

PROJECT_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-uoo(9irb!fcd5w-t7z*ua2go84_g4)b8q&8ofw*c)dabqoaf12'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['*']


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # project apps
    'main',

    # 3rd party apps
    'djmoney',
    'crispy_forms',
    "crispy_bootstrap5",
    'stripe',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    "whitenoise.middleware.WhiteNoiseMiddleware", # added whitenoise
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.realpath (PROJECT_DIR) + '/templates/',
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/5.1/ref/settings/#databases

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


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/5.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = 'static/'

STATICFILES_FINDERS = [
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]

STATICFILES_DIRS = [
    os.path.join(PROJECT_DIR, 'static'), # other project based static files
]

STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

# crispy forms template
CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"

CRISPY_TEMPLATE_PACK = "bootstrap5"

# stripe keys
STRIPE_SECRET_KEY = env('STRIPE_SECRET_KEY')
STRIPE_PUBLISHABLE_KEY = env('STRIPE_PUBLISHABLE_KEY')

STORAGES = {
    # ...
    "staticfiles": {
        "BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
    },
}

settings/staging.py:

import os, logging

from .base import *

import dj_database_url # postgre db_url


#  debug is true in staging environment
DEBUG = True

# installed apps for prod only
INSTALLED_APPS += [

]

# read secret key from environment variable
SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY")

# stripe api keys
STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY")
STRIPE_PUBLISHABLE_KEY = os.environ.get("STRIPE_PUBLISHABLE_KEY")


# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
# set to use postgre backend in production
DATABASES['default'] = dj_database_url.parse( os.environ.get("DATABASE_URL"),
                                                 conn_max_age=600)

requirements.txt

asgiref==3.8.1
babel==2.16.0
certifi==2024.8.30
charset-normalizer==3.3.2
crispy-bootstrap5==2024.2
dj-database-url==2.2.0
Django==4.2
django-crispy-forms==2.3
django-environ==0.11.2
django-money==3.5.3
gunicorn==23.0.0
idna==3.8
packaging==24.1
psycopg2-binary==2.9.9
py-moneyed==3.0
python-dateutil==2.9.0.post0
requests==2.32.3
six==1.16.0
sqlparse==0.5.1
stripe==10.10.0
typing_extensions==4.12.2
tzdata==2024.1
urllib3==2.2.2
whitenoise==6.7.0

version in DB: PostgreSQL 16.4

So cleary there is an issue with the connection backend, not clear what it is exactly. Difficult to replicate on localhost BUT I noticed and with the "migrate" command on localhost which I was about to find a way around.

Stacktrace:

2024-09-13T23:13:50.699 app[1857933f266d38] ams [info] [2024-09-13 23:13:50 +0000] [332] [INFO] Starting gunicorn 23.0.0

2024-09-13T23:13:50.700 app[1857933f266d38] ams [info] [2024-09-13 23:13:50 +0000] [332] [INFO] Listening at: http://0.0.0.0:8000 (332)

2024-09-13T23:13:50.700 app[1857933f266d38] ams [info] [2024-09-13 23:13:50 +0000] [332] [INFO] Using worker: sync

2024-09-13T23:13:50.703 app[1857933f266d38] ams [info] [2024-09-13 23:13:50 +0000] [337] [INFO] Booting worker with pid: 337

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] Internal Server Error: /admin/main/subscriptionplan/

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] Traceback (most recent call last):

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 187, in _get_session

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return self._session_cache

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] AttributeError: 'SessionStore' object has no attribute '_session_cache'

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] During handling of the above exception, another exception occurred:

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] Traceback (most recent call last):

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] response = get_response(request)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] response = wrapped_callback(request, *callback_args, **callback_kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/options.py", line 688, in wrapper

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return self.admin_site.admin_view(view)(*args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/decorators.py", line 134, in _wrapper_view

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] response = view_func(request, *args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapper_view_func

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] response = view_func(request, *args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 230, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] if not self.has_permission(request):

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 203, in has_permission

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return request.user.is_active and request.user.is_staff

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 266, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self._setup()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/functional.py", line 419, in _setup

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self._wrapped = self._setupfunc()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 25, in <lambda>

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] request.user = SimpleLazyObject(lambda: get_user(request))

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/middleware.py", line 11, in get_user

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] request._cached_user = auth.get_user(request)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 191, in get_user

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] user_id = _get_user_session_key(request)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/auth/__init__.py", line 60, in _get_user_session_key

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY])

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 53, in __getitem__

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return self._session[key]

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/backends/base.py", line 192, in _get_session

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self._session_cache = self.load()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 42, in load

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] s = self._get_session_from_db()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/contrib/sessions/backends/db.py", line 32, in _get_session_from_db

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return self.model.objects.get(

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/manager.py", line 87, in manager_method

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return getattr(self.get_queryset(), name)(*args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 633, in get

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] num = len(clone)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 380, in __len__

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self._fetch_all()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 1881, in _fetch_all

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self._result_cache = list(self._iterable_class(self))

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/query.py", line 91, in __iter__

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] results = compiler.execute_sql(

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1558, in execute_sql

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] cursor = self.connection.cursor()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return func(*args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 330, in cursor

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return self._cursor()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 306, in _cursor

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self.ensure_connection()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return func(*args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 289, in ensure_connection

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self.connect()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/utils/asyncio.py", line 26, in inner

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] return func(*args, **kwargs)

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 272, in connect

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self.init_connection_state()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 310, in init_connection_state

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] super().init_connection_state()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 239, in init_connection_state

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] self.check_database_version_supported()

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] File "/usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py", line 214, in check_database_version_supported

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] raise NotSupportedError(

2024-09-13T23:14:26.694 app[d8d9344a133778] ams [info] django.db.utils.NotSupportedError: PostgreSQL 12 or later is required (found 10.23).

Just like all comments you saw under your post, it is clear you are using a wrong DB instance.

Suggestion 1

Assuming we have the variable in our system environment variable, Try this:

echo DATABASE_URL

Based on the output you will clearly see what is the issue with it.

Lastly my suggestion will be for you to load your secrets in your settings.py file.

#settings.py

# Specify the path to your .env file
ENV_FILE_PATH = os.path.join(BASE_DIR, '.env')

# Read the .env file
environ.Env.read_env(ENV_FILE_PATH)

Suggestion 2:

Why not trying to use:

# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': env('DB_NAME'),
        'USER': env('DB_USER'),
        'PASSWORD': env('DB_PASSWORD'),
        'HOST': env('DB_HOST'),
        'PORT': env('DB_PORT'),
    }
}
Back to Top