Registry / testing / pytest-django

pytest-django

JSON →
library4.14.0pypypi✓ verified 29d ago

pytest-django is an active plugin for the pytest testing framework that enables efficient testing of Django projects and applications. It integrates pytest's powerful fixture system, reduced boilerplate, and advanced test capabilities with Django's ORM and components. The library maintains a regular release cadence, with multiple minor versions and occasional major updates throughout the year, ensuring compatibility with the latest Django and Python versions.

pip install pytest-django
INSTALL
IMPORT
SIG · PYTEST-DJANGO
P
pytest-django
testingpythonv4.14.0
Install
2.8s avg
Import
409ms
Disk
30MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.9–3.13
musl
3.9–3.13
Install & Compatibility
Where this runs
tested against v4.14.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.10–3.95 runs
installs and imports cleanly · install 0.0s · import 0.416s · 31.3MB
glibc
py 3.10–3.95 runs
installs and imports cleanly · install 2.8s · import 0.402s · 32MB
30MB installed
● package 30MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

pytest.mark.django_db
✓ import pytest @pytest.mark.django_db def test_my_database_function(): ...
Use this marker on test functions that require database access. This ensures Django's database setup and transaction management are applied.
settings (fixture)
✓ def test_with_custom_setting(settings): settings.DEBUG = True assert settings.DEBUG is True
✗ from myproject import settings # in a test settings.DEBUG = True
Always use the `settings` fixture to override Django settings within tests. Directly importing your project's `settings.py` module in tests will bypass `pytest-django`'s mechanisms and Django's `override_settings` which can lead to stale or incorrect setting values.
client (fixture)
✓ def test_my_view(client): response = client.get('/my-url/') assert response.status_code == 200
Provides an instance of `django.test.Client` for making requests in tests.
admin_client (fixture)
✓ def test_admin_view(admin_client): response = admin_client.get('/admin/') assert response.status_code == 200
Provides an instance of `django.test.Client` logged in as a superuser.

1. Create a `pytest.ini` file in your project root, specifying `DJANGO_SETTINGS_MODULE` to point to your Django settings file. This is crucial for pytest-django to set up the Django environment. 2. Define your Django models as usual. 3. Write test functions, using the `@pytest.mark.django_db` decorator or by requesting the `db` fixture for any test that interacts with the database. This enables transaction management and ensures tests are isolated. 4. Run tests with `pytest` in your project root.

# myproject/pytest.ini [pytest] DJANGO_SETTINGS_MODULE = myproject.settings python_files = tests.py test_*.py *_tests.py addopts = --reuse-db # myproject/myproject/settings.py (abbreviated) # ... standard Django settings ... INSTALLED_APPS = [ # ... 'myapp', # ... ] # myproject/myapp/models.py from django.db import models class Book(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) def __str__(self): return self.title # myproject/myapp/tests.py import pytest from myapp.models import Book @pytest.mark.django_db def test_book_creation(): # The 'db' fixture or 'pytest.mark.django_db' is required for database access. book = Book.objects.create(title='The Great Adventure', author='Jane Doe') assert Book.objects.count() == 1 assert book.title == 'The Great Adventure'
Debug
Known issues
breakingMajor versions of pytest-django often drop support for older, unsupported Python, Django, and pytest versions. Ensure your environment meets the minimum requirements for the pytest-django version you are installing.
fix
Always check the `pytest-django` changelog or documentation for specific compatibility requirements before upgrading. Upgrade Python, Django, or pytest as needed.
affects: All major versions (e.g., v4.0.0 dropped Python < 3.5, Django < 2.2, pytest < 5.4)
gotchaBy default, Django's `DEBUG` setting is set to `False` during test runs, regardless of its value in your settings file. This aligns with Django's default test runner behavior to simulate a production environment.
fix
If you need `DEBUG` to be `True` for specific tests, use the `settings` fixture to explicitly override it: `def test_my_feature(settings): settings.DEBUG = True`.
affects: All versions
gotchaTests that attempt to access the database without explicit permission will fail. `pytest-django` requires you to explicitly mark tests or request fixtures that need database access.
fix
Use the `@pytest.mark.django_db` decorator on your test functions, or request the `db`, `transactional_db`, or `django_db_reset_sequences` fixtures.
affects: All versions
gotchaIncorrectly configuring `DJANGO_SETTINGS_MODULE` can lead to import errors (`"could not import myproject.settings"`) or tests running without the proper Django environment.
fix
Specify `DJANGO_SETTINGS_MODULE` in your `pytest.ini` (e.g., `[pytest] DJANGO_SETTINGS_MODULE = yourproject.settings`), `pyproject.toml`, as an environment variable, or via the `--ds` command-line flag.
affects: All versions
gotchaUsing the `--reuse-db` option significantly speeds up test runs by keeping the database between sessions. However, it will not automatically pick up schema changes. If models are altered, the database schema will be out of sync.
fix
After making schema changes, run `pytest --create-db` (or `pytest --reuse-db --create-db`) once to force the test database to be re-created with the new schema. Subsequent runs can then use `--reuse-db` again.
affects: All versions
gotchaDirectly importing your Django project's `settings.py` module (e.g., `from myproject import settings`) in test files can cause issues with `pytest-django`'s setting overrides or when settings are dynamically configured.
fix
Always import `settings` from `django.conf` (e.g., `from django.conf import settings`) for general access, and use the `settings` pytest fixture to override individual settings within tests.
affects: All versions
gotchaAttempting to configure pytest options (such as `python_files`) by placing them directly in an executable Python script instead of standard configuration files can lead to a `SyntaxError` during test execution, preventing pytest-django from initializing.
fix
Always define pytest configuration options in standard pytest configuration files like `pytest.ini`, `pyproject.toml`, or `setup.cfg`. Ensure your test runner setup correctly invokes `pytest` and does not try to execute configuration files as Python scripts.
affects: All versions
gotchaA `SyntaxError` for configuration lines (e.g., `python_files = ...`) indicates that a `pytest` configuration file or a file containing `pytest` configurations (like `pytest.ini` or `pyproject.toml`) is being executed as a Python script, rather than being parsed by `pytest`. This prevents `pytest-django` from initializing correctly.
fix
Ensure `pytest` configuration files (`pytest.ini`, `pyproject.toml`) are correctly placed in your project's root and are not being run directly as Python scripts (e.g., via `python pytest.ini`). Run `pytest` from your project root, allowing it to automatically discover and parse its configuration files.
affects: All versions
Errors
Common errors & fixes
django.core.exceptions.ImproperlyConfigured: Requested settings, but settings have not been configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
Pytest-django cannot locate your Django project's settings file, preventing it from properly initializing the Django environment for your tests.
fix
Add the `DJANGO_SETTINGS_MODULE` entry to your `pytest.ini` file, pointing to your project's settings module.

```ini
# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = your_project_name.settings
# For example, if your settings are in 'myproject/settings.py'
# DJANGO_SETTINGS_MODULE = myproject.settings
```
Database access not allowed, use the "django_db" fixture to enable it.
Your test function is attempting to interact with the Django database (e.g., creating or querying models) without explicitly requesting a transactional database fixture from pytest-django.
fix
Add the `db` (or `django_db`) fixture as an argument to your test function to enable transactional database access for that test.

```python
import pytest
from myapp.models import MyModel

def test_my_model_creation(db):
    MyModel.objects.create(name="Test Item")
    assert MyModel.objects.count() == 1
```
pytest: error: fixture 'client' not found
Pytest cannot find the 'client' fixture (or other built-in `pytest-django` fixtures like `admin_client`, `user`), typically because `pytest-django` is not correctly configured or activated for your test run.
fix
Ensure `pytest-django` is installed and that your `DJANGO_SETTINGS_MODULE` is correctly specified in `pytest.ini` or as an environment variable, which allows `pytest-django` to initialize Django and provide its fixtures.

```ini
# pytest.ini
[pytest]
DJANGO_SETTINGS_MODULE = your_project_name.settings
```
Also, ensure that `pytest-django` is installed (`pip install pytest-django`) in your test environment.
Upgrade
Version history
4.14.0latest on PyPI · released Aug 10, 2026
Audit
Dependencies
pytestrequiredpytest-django is a plugin for pytest and automatically installs it. Requires pytest>=7.0.
Djangorequiredpytest-django is a testing plugin for Django. Compatible with Django 4.2, 5.1, 5.2, 6.0 and potentially newer versions.
Agent activity
13 hits · last 30 days
node
8
Amazon
1
Resources
pytest-django — pip install pytest-django · libregistry