Django Admin Search and Filters
Search and filters help staff find rows in the admin. A search box matches text, and a filter narrows the list.
Add search and a filter
The admin class names the search field and the filter field. Both use the title.
class PostAdmin(admin.ModelAdmin):
list_display = ["title"]
search_fields = ["title"]
list_filter = ["title"]Search for one post
The ask carries q=First. The list shrinks to one post.
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/blog/post/", {"q": "First"})
print(response.status_code)
print("1 post" in response.content.decode())Filter by one title
The ask carries title=First post. The list shrinks to one post again.
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/blog/post/", {"title": "First post"})
print(response.status_code)
print("1 post" in response.content.decode())Example
import django
from django.apps import AppConfig
from django.conf import settings
class BlogConfig(AppConfig):
name = "__main__"
label = "blog"
settings.configure(
DEBUG=True,
SECRET_KEY="key",
ROOT_URLCONF=__name__,
ALLOWED_HOSTS=["*"],
INSTALLED_APPS=[
"__main__.BlogConfig",
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
],
MIDDLEWARE=[
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [], "APP_DIRS": True, "OPTIONS": {"context_processors": ["django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages"]}}],
STATIC_URL="/static/",
)
django.setup()
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.management import call_command
from django.db import connection, models
from django.urls import path
class Post(models.Model):
title = models.CharField(max_length=100)
body = models.TextField()
class Meta:
app_label = "blog"
with connection.schema_editor() as editor:
editor.create_model(Post)
call_command("migrate", verbosity=0)
User.objects.create_superuser("sana", "sana@example.com", "secret123")
from django.test import Client
class PostAdmin(admin.ModelAdmin):
list_display = ["title"]
search_fields = ["title"]
list_filter = ["title"]
admin.site.register(Post, PostAdmin)
urlpatterns = [path("admin/", admin.site.urls)]
Post.objects.create(title="First post", body="Hello from Django.")
Post.objects.create(title="Second post", body="Models save rows.")
client = Client()
client.login(username="sana", password="secret123")
response = client.get("/admin/blog/post/")
print(response.status_code)
print("2 posts" in response.content.decode())
response = client.get("/admin/blog/post/", {"q": "First"})
print("1 post" in response.content.decode())
response = client.get("/admin/blog/post/", {"title": "First post"})
print("1 post" in response.content.decode())
Key points
- Set search_fields to the fields the search box matches.
- Search fields name text fields, like ["title"].
- Set list_filter to the fields that get a filter panel.
- A filter narrows the list to rows with one value.
- The search box and the filter both sit on the change list.
In this example, the setup lines configure Django. The blog app config gives the model an app to live in. The program creates the table directly. A real project uses migrations for this step. PostAdmin names title for the column, the search box, and the filter. Register ties the model to its admin class. Migrate builds the tables, and createsuperuser makes the admin account. Two create calls save two posts. The test client logs in and asks for the full list first. The prints show 200 and that the page says 2 posts. The search ask carries q=First, and the filter ask carries one title. Each print shows True, so each list holds one post.
Note
Search matches part of a value, so First finds First post.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
How do you add a search box to the admin change list?