Connect a Django application to Neon
To connect to Neon from a Django application Prerequisites. A Neon account and project with connection parameters ready Python 3.8+ installed An existing Django project (or create one with django admi...
Pre-built prompt for connecting Django applications to Neon
To connect to Neon from a Django application:
Prerequisites
Section titled “Prerequisites”- A Neon account and project with connection parameters ready
- Python 3.8+ installed
- An existing Django project (or create one with
django-admin startproject myproject)
important
Section titled “important”Always use a Python virtual environment. Do not install packages globally. If you do not have one set up, create and activate it before proceeding:
python3 -m venv venv
source venv/bin/activate # macOS / Linux
# venv\Scripts\activate # WindowsInstall the PostgreSQL driver
Section titled “Install the PostgreSQL driver”Install psycopg (the modern psycopg3 driver) and python-dotenv inside your virtual environment:
pip install "psycopg[binary]" python-dotenvThe docs examples below use psycopg (v3). If your project uses the older psycopg2 driver, see Connection issues for SNI compatibility requirements.
Create a Neon project
If you do not have one already, create a Neon project. Save your connection details including your password. They are required when defining connection settings.
To create a Neon project:
- Navigate to the Projects page in the Neon Console.
- Click New Project.
- Specify your project settings and click Create Project.
Configure Django connection settings
Connecting to Neon requires configuring database connection settings in your Django project's
settings.pyfile.note
To avoid the
endpoint ID is not specifiedconnection issue described here, be sure that you are using an up-to-date driver.In your Django project, navigate to the
DATABASESsection of yoursettings.pyfile and modify the connection details as shown:Python # Add these at the top of your settings.py from os import getenv from dotenv import load_dotenv load_dotenv() # Replace the DATABASES section of your settings.py with this DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': getenv('PGDATABASE'), 'USER': getenv('PGUSER'), 'PASSWORD': getenv('PGPASSWORD'), 'HOST': getenv('PGHOST'), 'PORT': getenv('PGPORT', 5432), 'OPTIONS': { 'sslmode': 'require', }, 'DISABLE_SERVER_SIDE_CURSORS': True, 'CONN_HEALTH_CHECKS': True, } }note
Neon places computes into an idle state and closes connections after 5 minutes of inactivity (see Compute lifecycle). To avoid connection errors, you can set the Django CONN_MAX_AGE setting to 0 to close database connections at the end of each request so that your application does not attempt to reuse connections that were closed by Neon. From Django 4.1, you can use a higher
CONN_MAX_AGEsetting in combination with the CONN_HEALTH_CHECKS setting to enable connection reuse while preventing errors that might occur due to closed connections. For more information about these configuration options, see Connection management, in the Django documentation.You can find all of the connection details listed above by clicking the Connect button in the Console nav to open the Connect to your branch modal. For more information, see Connect from any application.
Add a
.envfile to your project's root directory with the individual connection parameters (not a singleDATABASE_URL, since Django'sDATABASESsetting expects separate fields):Bash PGHOST="<endpoint_hostname>.neon.tech" PGDATABASE="<dbname>" PGUSER="<user>" PGPASSWORD="<password>" PGPORT=5432Replace
<endpoint_hostname>,<dbname>,<user>, and<password>with your actual database credentials.For additional information about Django project settings, see Django Settings: Databases, in the Django documentation.
Test the connection
Create a simple view to verify the database connection is working.
- In your project's main app directory (next to
urls.py), createviews.py:Python from django.http import JsonResponse from django.db import connection def db_version(request): with connection.cursor() as cursor: cursor.execute("SELECT version();") version = cursor.fetchone()[0] return JsonResponse({'version': version}) - Add a URL route in your project's
urls.py:Python from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.db_version, name='db_version'), ] - Run migrations and start the server:
Bash python manage.py migrate python manage.py runserver - Visit
http://localhost:8000to see the PostgreSQL version from your Neon database.
- In your project's main app directory (next to
Connection issues
Section titled “Connection issues”-
Django uses the
psycopg2driver as the default adapter for Postgres. If you have an older version of that driver, you may encounter anEndpoint ID is not specifiederror when connecting to Neon. This error occurs if the client library used by your driver does not support the Server Name Indication (SNI) mechanism in TLS, which Neon uses to route incoming connections. Thepsycopg2driver uses thelibpqclient library, which supports SNI as of v14. You can check yourpsycopg2andlibpqversions by starting a Django shell in your Django project and running the following commands:Bash # Start a Django shell python3 manage.py shell # Check versions import psycopg2 print("psycopg2 version:", psycopg2.__version__) print("libpq version:", psycopg2._psycopg.libpq_version())The version number for
libpqis presented in a different format, for example, version 14.1 will be shown as 140001. If yourlibpqversion is less than version 14, you can either upgrade yourpsycopg2driver to get a newerlibpqversion or use one of the workarounds described in our Connection errors documentation. Upgrading yourpsycopg2driver may introduce compatibility issues with your Django or Python version, so you should test your application thoroughly. -
If you encounter an
SSL SYSCALL error: EOF detectedwhen connecting to the database, this typically occurs because the application is trying to reuse a connection after the Neon compute has been suspended due to inactivity. To resolve this issue, try one of the following options:- Set your Django
CONN_MAX_AGEsetting to a value less than or equal to the scale to zero setting configured for your compute. The default is 5 minutes (300 seconds). - Enable
CONN_HEALTH_CHECKSby setting it totrue. This forces a health check to verify that the connection is alive before executing a query.
For information configuring Neon's Scale to zero setting, see Configuring Scale to zero for Neon computes.
- Set your Django
Schema migration with Django
Section titled “Schema migration with Django”For schema migration with Django, see our guide:
Django application blog post and sample application
Section titled “Django application blog post and sample application”Learn how to use Django with Lakebase Postgres with this blog post and the accompanying sample application.
Blog Post: Using Django with Neon Learn how to build a Django application with Lakebase Postgres
Django sample application Django with Lakebase Postgres
Community resources
Section titled “Community resources”Notes for AI-assisted setup
- Do not install packages globally. Always use a virtual environment and run commands with
venv/bin/pipandvenv/bin/python(or the activated equivalent). - Use
psycopg[binary](psycopg v3), not the olderpsycopg2. If the project already usespsycopg2, check the Connection issues section for SNI compatibility. - Include
CONN_HEALTH_CHECKS: Truein theDATABASESconfiguration. This prevents errors from idle connections when Neon scales to zero. - Do not hardcode credentials in
settings.py. Use environment variables viapython-dotenvandos.getenv(). For more information, see Security overview. - The
.envfile should use individualPG*variables (PGHOST,PGDATABASE, etc.), not a singleDATABASE_URL, since Django's database configuration expects separate fields.
Next steps
Section titled “Next steps”- Add Object Storage: S3-compatible file storage that branches with your database.
- Call an LLM with AI Gateway: Access foundation models from Anthropic, OpenAI, Google, and more with one credential.
Need help?
Section titled “Need help?”Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.