October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

Pytest-Django Tutorial: How to Test Django Applications

A practical pytest-django tutorial covering setup, Django settings, database access, fixtures, test database reuse, and common failures.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
[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.

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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshoot common setup and test failures

  • Django settings are not configured: Set DJANGO_SETTINGS_MODULE in pytest configuration or the environment, or pass it with --ds for that run. Confirm that the module path matches your project.
  • Pytest reports that database access is not allowed: Add @pytest.mark.django_db or request db for 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=True or transactional_db when the test requires real transaction boundaries. Expect the additional database flush work.
  • A live_server test 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_files patterns 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-db to 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.

Further pytest-django references

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.