[Solved]-Django can't drop database: psycopg2.OperationalError: cannot drop the currently open database

28👍

TL;DR

If you just want the solution, here it is.
Make sure that your Postgres server has a “postgres” database. You can check by connecting via psql, and running /list or /l. You can create the database by running: CREATE DATABASE postgres in psql.

Extended

Django prefers to not run “initialization queries” (presumably things like creating the test database) from the “default” database specified in your DATABASES setting. This is presumed to be the production database, so it would be in Django’s best interests to not mess around there.

This is why at the beginning of the tests, this is shown (ignore my filesystem):

    /Users/dcgoss/Desktop/Pickle/PickleBackend/venv/lib/python3.4/site-packages/django/db/backends/postgresql/base.py:247: 
    RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed 
    (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the default database instead.
    RuntimeWarning

Django looks for a database named “postgres” on the host specified in your DATABASES settings, this is where it runs the queries to create and delete your test database. (Note: Django does not need the “postgres” database to be explicitly specified in your settings, it just looks for it on whatever database server is specified in your settings).

It appears that if this “postgres” database does not exist, Django can create the test database and run the tests, but it cannot delete the test database. This may be because Postgres does not allow you to drop the database you are currently connected to, however to me it seems that there is no reason that Django couldn’t just drop the test database from the “default” (production) database specified in the settings. I presume it is using the “default” database to create the test database, so it seems there’s no reason why it can’t delete it as well.

Regardless, the solution was just to create that “postgres” database with a simple SQL statement: CREATE DATABASE postgres. After that database was created, everything worked fine.

👤dcgoss

7👍

If postgres database exists, try adding access to ‘postgres’ database in pg_hba.conf. Refer: https://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html

0👍

You might want to add postgres database to the list of database in pgbouncer.ini file, if you’re using pgbouncer with postgresql

Leave a comment