To test a Django application with pytest, install pytest-django, point it to your Django settings, then run pytest. Add database access only to tests that need it, using the django_db marker or the db fixture. This guide follows the pytest-django project’s current getting-started and reference documentation, accessed October 3, 2026; check syntax against the versions installed in your project.
Install pytest-django and configure Django settings
Run the installation command in the same virtual environment as your project:
python -m pip install pytest-django
If you also want the installation to ensure Django is installed as a dependency, the project tutorial documents the optional django extra:
python -m pip install 'pytest-django[django]'
Set the settings module so pytest-django knows which Django project to initialize. For example, if your settings module is yourproject.settings, add this to a root-level pytest.ini:
Recommended Free Tools
#1 Best Overall
[pytest]
DJANGO_SETTINGS_MODULE = yourproject.settings
You can also configure pytest in pyproject.toml, set DJANGO_SETTINGS_MODULE in the environment, or pass a settings module for one run with --ds. See the pytest-django getting-started guide for the documented configuration forms.
If your project uses Django’s common test-file naming, you may configure discovery explicitly:
[pytest]
DJANGO_SETTINGS_MODULE = yourproject.settings
python_files = tests.py test_*.py *_tests.py
Before adding or changing python_files, inspect the existing pytest configuration: an overly narrow pattern can prevent pytest from finding tests already in the project.
Rank #2
Write a first test and run it
For example, a test that checks a view’s response can use pytest-django’s client fixture. Replace the URL with a route in your application:
def test_homepage_returns_success(client):
response = client.get("/")
assert response.status_code == 200
Save the test in a file pytest discovers, such as tests/test_views.py, then run the suite from the project directory:
pytest
pytest-django can generally discover standard Django and Nose-style test suites with little or no extra configuration. If a test is not collected, verify the file and function naming against your discovery configuration before changing the test itself.
Allow database access only where needed
pytest-django deliberately blocks database access unless the test requests it. The project describes this as a conservative approach: database-dependent behavior is explicit rather than silently enabled for every test. See the database documentation.
Use rollback-based isolation for ordinary ORM tests
Mark a test that uses the ORM with @pytest.mark.django_db:
import pytest
@pytest.mark.django_db
def test_product_can_be_saved():
product = Product.objects.create(name="Notebook")
assert Product.objects.get(pk=product.pk).name == "Notebook"
Alternatively, request the db fixture in the test function’s arguments. Ordinary database-enabled tests use rollback-based isolation comparable to Django’s TestCase.
Use transactional mode for real transaction behavior
When the behavior under test depends on actual transaction boundaries, mark the test with @pytest.mark.django_db(transaction=True) or request transactional_db. Transactional tests are slower because the database must be flushed between tests, so use them when transaction semantics matter rather than as the default.
Request the databases a test needs
By default, the marker requests only the default database. For a test that uses a specific configured database, pass it explicitly with the marker’s databases argument. The documented __all__ shortcut requests all configured databases. Consult the plugin’s database guide for details and version-specific syntax.
Choose fixtures by the behavior under test
pytest-django supplies fixtures for common Django testing tasks. Use the least complex fixture and database mode that covers the behavior you need:
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteBest Value
| Testing need | Fixture or approach | What it does |
|---|---|---|
| Make an in-process request and inspect the response | client |
Provides Django’s test client for request/response tests. |
| Exercise an asynchronous request | async_client |
Provides the async test client where appropriate. |
| Change a setting for one test | settings |
Lets the test adjust Django settings; changes are reverted automatically. |
| Write app tests that support custom user models | django_user_model |
Provides the project’s configured user model, avoiding a hard-coded import of Django’s default user. |
| Construct a request directly instead of making a client request | rf or async_rf |
Provides a request factory for synchronous or asynchronous requests. |
| Test through a background Django server and HTTP client | live_server |
Starts a live server for the test; it uses transactional database behavior. |
Fixture behavior and usage are documented in the pytest-django helper reference. In particular, a test using live_server needs transactional database behavior because the server and test run in separate threads and cannot share one transaction.
Reuse or recreate the test database
Creating a test database can add setup work to repeat runs. pytest-django documents --reuse-db to keep and reuse the test database between runs, and --create-db to force it to be recreated:
pytest --reuse-db
pytest --create-db
After schema changes, recreate the database with --create-db rather than assuming a reused test database reflects the current schema.
The plugin also documents --no-migrations (also written --nomigrations) to create the test database by inspecting models instead of applying migrations. Use that mode only if the tradeoff suits your project; --migrations forces migrations back on. These options and database lifecycle behavior are covered in the database guide.
Free tools Windows power users keep installed
One-click scans. No signup required.
Troubleshoot common setup and test failures
- Django settings are not configured: Set
DJANGO_SETTINGS_MODULEin pytest configuration or the environment, or pass it with--dsfor that run. Confirm that the module path matches your project. - Pytest reports that database access is not allowed: Add
@pytest.mark.django_dbor requestdbfor the test that performs ORM work. Do not enable database access indiscriminately across unrelated tests. - A transaction-dependent test behaves differently from an ordinary ORM test: Use
transaction=Trueortransactional_dbwhen the test requires real transaction boundaries. Expect the additional database flush work. - A
live_servertest encounters database or transaction issues: Account for its transactional behavior; the separate server and test threads cannot share one transaction. - Tests are not collected: Check the file names against pytest’s configured
python_filespatterns and the project’s existing configuration before adding a new pattern. - Tests pass before a schema change but fail with a reused test database afterward: Run
pytest --create-dbto force recreation.
Or skip the browser setup
If a Django test needs a screenshot of a page, a browser-based capture can involve setup beyond pytest itself. ScreenshotNeo is a website screenshot API and MCP server; its clean-shot flow accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture. Each step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in headers. AI agents can use its MCP server tools, including take_screenshot, get_page_info, and capture_pdf. See ScreenshotNeo and its API documentation.
One GET request returns a screenshot; this cURL example saves a WebP capture of the test server URL you supply:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://your-test-host.example/ -o shot.webp
The target must be reachable by the service. For local development, use a reachable test or staging URL rather than assuming an external service can access a machine-bound localhost address. ScreenshotNeo offers 1,000 screenshots per month free with no card; paid plans start at $5 for 3,000. Sign up for ScreenshotNeo.
Quick Recap
Further pytest-django references
- Getting started and configuration
- Database access and test database options
- Fixtures and helper reference
- pytest-django documentation
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →




