[Fixed]-Force delete of any previous test database (autoclobber) when running Django unit tests, eg, in PyCharm


My answer was to create a script like this:

export PGPASSWORD=the_password
if [[ `psql  -h -d postgres -U username -p 5432 -tAc "SELECT 1 FROM pg_database WHERE datname='test_djangoprojectname'"` == "1" ]]
    psql -h -d postgres -U username -p 5432 -a -w -c "SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = 'test_djangoprojectname' AND pid <> pg_backend_pid();"
    psql -h -d postgres -U username -p 5432 -a -w -c "DROP DATABASE test_djangoprojectname;"
  • The -d setting is database name – it can be any database your user has access to, except the one you are deleting.
  • The default username is postgres.
  • The -p setting is the port your database is on – 5432 is the default.

Save as (for example) del_test_db.sh (Windows users see below), then

chmod +x del_test_db.sh

Then in PyCharm:

  1. Run, Edit Configurations…
  2. Unfold Defaults, click Django tests
  3. In the Before launch window click +, External tools, click +
  4. Under Program, select your file del_test_db.sh, give the command a name (eg, ‘del test db’) and click OK.
  5. Select your tool in the list and click OK
  6. You may need to unfold Django tests in the left and delete existing test configurations

Then the script force deletes the test database before every run.

This works on Mac OS X and Ubuntu etc. For Windows the process is the same, except instead of export use SET, save the commands as a .bat file instead of .sh, and you don’t need to chmod +x, and use the following syntax for the IF statement in the batch file:

if 'command' == '1' (

Apologies I’m unable to check this as I don’t have a Windows machine.

Thanks to this answer for the code checking whether the database exists.



In Pycharm django tests, you can enable the option input and enter --noinput

see screenshot below

enter image description here


If you’re using PyCharm and want to run a single test using the green arrow but you keep getting this error, you can modify the default django tests configuration template, so that you don’t have to keep setting the --noinput option on each.

enter image description here


If you are using flush in some other way, (eg, on the pre-existing development database like here), the --noinput option supresses the user prompt, eg:

from django.core.management import call_command
call_command('flush', '--noinput')

Leave a comment