HTMX Active Search
Learn about HTMX Active Search
What is Active Search?
Active search (also called live search or instant search) is a pattern where results are filtered and displayed in real time as the user types into a search box. Traditionally this requires significant JavaScript code, but with HTMX it takes just a few HTML attributes.
Adding the Search Input
In your contact_list.html template, add a text input field above the contact list. Give it a name attribute of "search" and add the following HTMX attributes: hx-get pointing to a search URL, hx-trigger set to "keyup changed delay:300ms" to debounce the input, and hx-target pointing to the element that should be updated with the search results.
Creating the Search View
In views.py, create a new view called search_contacts. This view reads the "search" query parameter from the request. It then filters the Contact queryset using Django's Q objects to search across the first_name, last_name, and email fields simultaneously. The search uses __icontains for case-insensitive partial matching.
Returning a Partial Template
Instead of returning an entire HTML page, the search view returns only the contact list fragment — just the rows or cards, without the base template wrapper. Create a partial template called contact_list_partial.html that contains only the for loop and contact display markup. This is the key to HTMX's efficiency: the server sends back only the HTML that needs to change.
Wiring Up the URL
Add a new URL pattern in contacts/urls.py that maps a path like "search/" to the search_contacts view. This is the endpoint that HTMX will call every time the user types in the search box.
Testing the Live Search
Start the development server and navigate to the contact list page. Begin typing a name into the search field. After a 300ms delay, HTMX automatically makes a GET request to the search endpoint and swaps the returned HTML into the target element. The contacts are filtered instantly without a full page reload.