[Fixed]-Django Test — Unable to drop and recreate test database

8👍

sudo /etc/init.d/postgresql restart may be a restart will solve this issue

5👍

In terminal, run:

ps aux | grep postgres

This will output different processes that are running using postgres, such as:

my_user 5983 0.0 0.0 7325299 4583 ?? Ss 3:15PM 0:00.02 postgres: my_user test_myproj [local] idle

Find the process running test_myproj, and that process’s correspondent ID, which is 5983 in this example. Kill this process by running:

kill -9 5983

4👍

I found a useful answer here ported by CHUCKCMARTIN

To sum up, you need to run this code to make it available again.

from django.core.management.base import BaseCommand
from django.db import connection
from django.conf import settings
cursor = connection.cursor()
database_name = 'test_<FAILING_DB_NAME>'
cursor.execute(
    "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity "
    "WHERE pg_stat_activity.datname = %s AND pid <> pg_backend_pid();", [database_name])
👤morkun

0👍

There is 1 other session using the database.

Have seen this message when the test database was open in pg admin ui and trying to run django tests at same time. Before dropping the db django/psycopg2 checks if there are any sessions active on that db. Closed the connection to the server in pg admin and it just works. Check if you have a connection to the db in shell or ui. Should not need to restart server.

0👍

I faced the same issue while trying to run some unit tests from pycharm. As previously mentioned, restarting my postgres solved the issue for me.

If someone is using a docker container, the command you will need to use is,

docker-compose restart postgresql-11

postgresql-11 is the name of my PostgreSQL database server name.

👤Priom

Leave a comment