Skip to content
Latchkey

pytest-django "Database access not allowed, use the django_db mark" in CI

pytest-django blocks database access by default so tests that touch the ORM are explicit. A test queried or saved a model without the django_db mark (or a fixture that provides it), so pytest-django raised rather than let it hit the DB.

What this error means

A test fails with "Failed: Database access not allowed, use the \"django_db\" mark, or the \"db\" or \"transactional_db\" fixtures to enable it."

pytest
Failed: Database access not allowed, use the "django_db" mark, or the "db" or
"transactional_db" fixtures to enable it.

Common causes

The test touches the ORM without the mark

A test creates or queries a model but is not decorated with @pytest.mark.django_db, so pytest-django refuses DB access.

A fixture accesses the DB without requesting db

A fixture builds model instances but does not depend on the db fixture, so access is blocked when the test runs.

How to fix it

Mark tests that need the database

Add the django_db mark to tests (or use the db fixture) that read or write models.

tests/test_thing.py
import pytest

@pytest.mark.django_db
def test_creates_thing():
    Thing.objects.create(name="x")
    assert Thing.objects.count() == 1

Request the db fixture in DB-using fixtures

A fixture that persists objects must depend on db so access is enabled.

tests/conftest.py
import pytest

@pytest.fixture
def thing(db):
    return Thing.objects.create(name="x")

How to prevent it

  • Add @pytest.mark.django_db to any test that touches the ORM.
  • Make DB-using fixtures depend on the db fixture.
  • Keep DB access explicit so slow or stateful tests are obvious.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →