Why can't django connect to postgres managed database?

Posted November 10, 2020 4.1k views
DigitalOcean Managed PostgreSQL Database

Greetings, are there any settings or other libraries I need to install to get my remote database from Digital Ocean to work with Django? I can connect to the database just fine, but when I connect through Django I get a failure which says:

Connecting to the PostgreSQL database...
could not connect to server: Connection timed out (0x0000274C/10060)
        Is the server running on host "ADDRESS" (IP) and accepting
        TCP/IP connections on port 5432?

How can I edit the managed postgres server from Digital Ocean to allow the connections?

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Submit an Answer
1 answer

If you are using a managed database then the default port and host differ from the usual port 5432.

You can test the connection using Python directly with a command like this:

python3 -c 'import psycopg2 as db; conn = db.connect("postgresql://doadmin:<your_password>@<your_hostname>:25060/<your_database>?sslmode=require"); print(conn.get_backend_pid()); conn.close()'

Be sure to substitute values in place of:

  • <your_password>
  • <your_hostname>
  • <your_database>

Also make sure that you have the psycopg2 library installed for your Linux distribution.

It is easiest to get the entire connection string from the control panel under your database’s ‘Connection Details’ tab. Pick the Connection string item from the top right of the pane.

If you can connect, then you will receive output like 532605 - the number will be different, but in general, if you get a process ID from the database it means that you can connect.

If you receive an error, be sure that the IP address of your machine or droplet is in the list that is allowed to connect to the database.

Testing like this will avoid Django and test the connection directly. From here you can determine whether there is an issue with your Django settings or the database in general.