{"id":1298,"library":"pytest-django","title":"pytest-django","description":"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.","status":"active","version":"4.12.0","language":"python","source_language":"en","source_url":"https://github.com/pytest-dev/pytest-django","tags":["pytest","django","testing","plugin","python"],"install":[{"cmd":"pip install pytest-django","lang":"bash","label":"Install latest version"}],"dependencies":[{"reason":"pytest-django is a plugin for pytest and automatically installs it. Requires pytest>=7.0.","package":"pytest","optional":false},{"reason":"pytest-django is a testing plugin for Django. Compatible with Django 4.2, 5.1, 5.2, 6.0 and potentially newer versions.","package":"Django","optional":false}],"imports":[{"note":"Use this marker on test functions that require database access. This ensures Django's database setup and transaction management are applied.","symbol":"pytest.mark.django_db","correct":"import pytest\n\n@pytest.mark.django_db\ndef test_my_database_function():\n    ..."},{"note":"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.","wrong":"from myproject import settings # in a test\nsettings.DEBUG = True","symbol":"settings (fixture)","correct":"def test_with_custom_setting(settings):\n    settings.DEBUG = True\n    assert settings.DEBUG is True"},{"note":"Provides an instance of `django.test.Client` for making requests in tests.","symbol":"client (fixture)","correct":"def test_my_view(client):\n    response = client.get('/my-url/')\n    assert response.status_code == 200"},{"note":"Provides an instance of `django.test.Client` logged in as a superuser.","symbol":"admin_client (fixture)","correct":"def test_admin_view(admin_client):\n    response = admin_client.get('/admin/')\n    assert response.status_code == 200"}],"quickstart":{"code":"# myproject/pytest.ini\n[pytest]\nDJANGO_SETTINGS_MODULE = myproject.settings\npython_files = tests.py test_*.py *_tests.py\naddopts = --reuse-db\n\n# myproject/myproject/settings.py (abbreviated)\n# ... standard Django settings ...\nINSTALLED_APPS = [\n    # ...\n    'myapp',\n    # ...\n]\n\n# myproject/myapp/models.py\nfrom django.db import models\n\nclass Book(models.Model):\n    title = models.CharField(max_length=200)\n    author = models.CharField(max_length=100)\n\n    def __str__(self):\n        return self.title\n\n# myproject/myapp/tests.py\nimport pytest\nfrom myapp.models import Book\n\n@pytest.mark.django_db\ndef test_book_creation():\n    # The 'db' fixture or 'pytest.mark.django_db' is required for database access.\n    book = Book.objects.create(title='The Great Adventure', author='Jane Doe')\n    assert Book.objects.count() == 1\n    assert book.title == 'The Great Adventure'","lang":"python","description":"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.\n2. Define your Django models as usual.\n3. 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.\n4. Run tests with `pytest` in your project root."},"warnings":[{"fix":"Always check the `pytest-django` changelog or documentation for specific compatibility requirements before upgrading. Upgrade Python, Django, or pytest as needed.","message":"Major 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.","severity":"breaking","affected_versions":"All major versions (e.g., v4.0.0 dropped Python < 3.5, Django < 2.2, pytest < 5.4)"},{"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`.","message":"By 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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Use the `@pytest.mark.django_db` decorator on your test functions, or request the `db`, `transactional_db`, or `django_db_reset_sequences` fixtures.","message":"Tests 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Incorrectly configuring `DJANGO_SETTINGS_MODULE` can lead to import errors (`\"could not import myproject.settings\"`) or tests running without the proper Django environment.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Using 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Directly 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"Attempting 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.","severity":"gotcha","affected_versions":"All versions"},{"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.","message":"A `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.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"search_vec":"'activ':9 'advanc':35 'applic':24 'boilerpl':33 'cadenc':50 'capabl':37 'compat':63 'compon':43 'django':3,6,21,39,67,72 'effici':18 'enabl':17 'ensur':62 'fixtur':30 'framework':15 'integr':26 'latest':66 'librari':45 'maintain':46 'major':57 'minor':53 'multipl':52 'occasion':56 'orm':41 'plugin':10,74 'power':29 'project':22 'pytest':2,5,13,27,71 'pytest-django':1,4 'python':69,75 'reduc':32 'regular':48 'releas':49 'system':31 'test':14,19,36,73 'throughout':59 'updat':58 'version':54,70 'year':61","created_at":"2026-04-08T04:58:08.611888+00:00","updated_at":"2026-04-16T19:59:53.365602+00:00","problems":[{"fix":"Add the `DJANGO_SETTINGS_MODULE` entry to your `pytest.ini` file, pointing to your project's settings module.\n\n```ini\n# pytest.ini\n[pytest]\nDJANGO_SETTINGS_MODULE = your_project_name.settings\n# For example, if your settings are in 'myproject/settings.py'\n# DJANGO_SETTINGS_MODULE = myproject.settings\n```","cause":"Pytest-django cannot locate your Django project's settings file, preventing it from properly initializing the Django environment for your tests.","error":"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."},{"fix":"Add the `db` (or `django_db`) fixture as an argument to your test function to enable transactional database access for that test.\n\n```python\nimport pytest\nfrom myapp.models import MyModel\n\ndef test_my_model_creation(db):\n    MyModel.objects.create(name=\"Test Item\")\n    assert MyModel.objects.count() == 1\n```","cause":"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.","error":"Database access not allowed, use the \"django_db\" fixture to enable it."},{"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.\n\n```ini\n# pytest.ini\n[pytest]\nDJANGO_SETTINGS_MODULE = your_project_name.settings\n```\nAlso, ensure that `pytest-django` is installed (`pip install pytest-django`) in your test environment.","cause":"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.","error":"pytest: error: fixture 'client' not found"}],"ecosystem":"pypi","meta_description":null,"install_score":100,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":"4.14.0","cli_name":"","cli_version":null,"type":"library","homepage":null,"github":"https://github.com/pytest-dev/pytest-django","docs":"https://pytest-django.readthedocs.io/","changelog":"https://pytest-django.readthedocs.io/en/latest/changelog.html","pypi":"https://pypi.org/project/pytest-django/","npm":null,"openapi_spec":null,"status_page":null,"smithery":null,"categories":["testing","web-framework","database"],"base_url":null,"auth_type":null,"provenance":{"verified_status":"passing","verified_at":"2026-06-28","last_verified":"2026-08-27","next_check":"2026-07-28","install_tag":"verified"}}