CARVIEW |
Select Language
HTTP/2 200
date: Sun, 12 Oct 2025 00:10:15 GMT
server: Fly/6f91d33b9d (2025-10-08)
content-type: text/html; charset=utf-8
content-encoding: gzip
via: 2 fly.io, 2 fly.io
fly-request-id: 01K7AW1WGWHHW2ZAQ1VQN05CDK-bom
Writing tests for the Django admin with pytest-django | Simon Willison’s TILs
Writing tests for the Django admin with pytest-django
I'm using pytest-django on a project and I wanted to write a test for a Django admin create form submission. Here's the pattern I came up with:
from .models import Location
import pytest
def test_admin_create_location_sets_public_id(client, admin_user):
client.force_login(admin_user)
assert Location.objects.count() == 0
response = client.post(
"/admin/core/location/add/",
{
"name": "hello",
"state": "13",
"location_type": "1",
"latitude": "0",
"longitude": "0",
"_save": "Save",
},
)
# 200 means the form is being re-displayed with errors
assert response.status_code == 302
location = Location.objects.order_by("-id")[0]
assert location.name == "hello"
assert location.public_id == "lc"
The trick here is to use the client
and admin_user
pytest-django fixtures (documented here) to get a configured test client and admin user object, then use client.force_login(admin_user)
to obtain a session where that user is signed-in to the admin. Then write tests as normal.
Using the admin_client fixture
Even better: use the admin_client
fixture provided by pytest-django
which is already signed into the admin:
def test_admin_create_location_sets_public_id(admin_client):
response = admin_client.post(
"/admin/core/location/add/",
# ...
Before finding out that this was included I implemented my own version of it:
import pytest
@pytest.fixture()
def admin_client(client, admin_user):
client.force_login(admin_user)
return client
# Then write tests like this:
def test_admin_create_location_sets_public_id(admin_client):
response = admin_client.post(
"/admin/core/location/add/",
# ...
Related
- django Using pytest-django with a reusable Django application - 2024-08-07
- django Show the timezone for datetimes in the Django admin - 2021-03-02
- cookiecutter Testing cookiecutter templates with pytest - 2021-01-27
- pytest Start a server in a subprocess during a pytest session - 2020-08-31
- pytest Mocking Stripe signature checks in a pytest fixture - 2024-07-01
- pytest Registering temporary pluggy plugins inside tests - 2020-07-21
- pytest Using pytest and Playwright to test a JavaScript web application - 2022-07-24
- pytest Using namedtuple for pytest parameterized tests - 2024-08-31
- pytest Session-scoped temporary directories in pytest - 2020-04-26
- datasette Using pytest-httpx to run intercepted requests through an in-memory Datasette instance - 2023-07-24
Created 2021-03-02T13:08:34-08:00, updated 2021-03-02T23:37:18-08:00 · History · Edit