django/django · critical · CommandError
Database %s couldn't be flushed. Possible reasons: * The d
Error message
Database %s couldn't be flushed. Possible reasons: * The database isn't running or isn't configured correctly. * At least one of the expected database tables doesn't exist. * The SQL was invalid. Hint: Look at the output of 'django-admin sqlflush'. That's the SQL this command wasn't able to run.
What it means
Raised by the flush command when connection.ops.execute_sql_flush(sql_list) raises any exception (flush.py:70-81). The command generates SQL via sql_flush() (DELETE/TRUNCATE/RESET SEQUENCE statements) and runs it atomically; failure is re-raised as CommandError chaining the original via `from exc`. The hint points to `django-admin sqlflush` because that prints the exact SQL bundle that failed, letting you inspect which statement broke.
Source
Thrown at django/core/management/commands/flush.py:73
reset_sequences=reset_sequences,
allow_cascade=allow_cascade,
)
if interactive:
confirm = input("""You have requested a flush of the database.
This will IRREVERSIBLY DESTROY all data currently in the "%s" database,
and return each table to an empty state.
Are you sure you want to do this?
Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict["NAME"])
else:
confirm = "yes"
if confirm == "yes":
try:
connection.ops.execute_sql_flush(sql_list)
except Exception as exc:
raise CommandError(
"Database %s couldn't be flushed. Possible reasons:\n"
" * The database isn't running or isn't configured correctly.\n"
" * At least one of the expected database tables doesn't exist.\n"
" * The SQL was invalid.\n"
"Hint: Look at the output of 'django-admin sqlflush'. "
"That's the SQL this command wasn't able to run."
% (connection.settings_dict["NAME"],)
) from exc
# Empty sql_list may signify an empty database and post_migrate
# would then crash.
if sql_list and not inhibit_post_migrate:
# Emit the post migrate signal. This allows individual
# applications to respond as if the database had been migrated
# from scratch.
emit_post_migrate_signal(verbosity, interactive, database)
else:
self.stdout.write("Flush cancelled.")View on GitHub (pinned to ae25a40be0)
Solutions
- Run `python manage.py migrate` first so all expected tables exist, then retry flush.
- Run `django-admin sqlflush` (or `python manage.py sqlflush`) and execute statements manually to find the exact failing SQL and DB error.
- Check DB user grants: the role needs DELETE/TRUNCATE/ALTER SEQUENCE on the relevant tables.
- Confirm the DB is reachable: `python manage.py dbshell` or check connection settings in DATABASES.
- If caused by FK constraints, ensure sql_flush emits statements in the right order for your backend (report a backend bug if not).
Example fix
// before python manage.py flush --noinput // after python manage.py migrate python manage.py flush --noinput
Defensive patterns
Strategy: validation
Validate before calling
from django.db import connections
from django.core.management import call_command
conn = connections['default']
# Ensure schema exists before flushing
with conn.cursor() as cur:
cur.execute('SELECT 1') # raises if DB unreachable
# Run migrations first so expected tables exist
call_command('migrate', interactive=False) Type guard
def db_ready_for_flush(alias='default') -> bool:
from django.db import connections
conn = connections[alias]
try:
with conn.cursor() as cur:
cur.execute('SELECT 1')
return True
except Exception:
return False Try / catch
from django.core.management.base import CommandError
from django.core.management import call_command
try:
call_command('flush', interactive=False)
except CommandError as e:
# Inspect `python manage.py sqlflush` output, fix schema/grants, retry
logger.error('Flush failed; run `manage.py sqlflush` to inspect SQL: %s', e)
raise Prevention
- Always run `migrate` before `flush` so expected tables exist.
- Grant the DB role DELETE/TRUNCATE/ALTER SEQUENCE privileges.
- Never run flush against a DB you cannot afford to wipe; it is irreversible.
When it happens
Trigger: Running `python manage.py flush` when migrations have not been applied (expected tables missing); flushing a DB the process lacks DELETE/TRUNCATE privileges on; a foreign-key constraint blocks a DELETE ordering error; the DB server is unreachable mid-command; a third-party backend producing invalid SQL.
Common situations: Fresh clone where someone ran `flush` before `migrate`; running flush in CI against a shared DB with restricted grants; switching DB engines (sqlite->postgres) without migrating; tables manually dropped outside Django leaving schema inconsistent.
Related errors
- aborted
- user '%s' does not exist
- Aborting password change for user '%s' after %s attempts
- Session engine '%s' doesn't support clearing expired session
- 'no_color' and 'force_color' can't be used together.
AI-assisted analysis of django/django@ae25a40be0 (2026-08-06).
Data as JSON: /api/errors/0b4bfdb80f4edaef.
Report an issue: GitHub.