Add instant database search with Django and HTMX 🕵️

We'll create a fast and simple database search using Django and HTMX. It's easy and fast to do with HTMX.

There'll be 6 steps, plus a bonus at the end.

Here's a optional video tutorial (with me 👋) that follows the written guide below.


If you include your bonus, your final product will look like below. Let's go 🚀

Your instant, simple database search

Project Setup

First, create a new Django project and a new app. I'm calling my app 'sim'.

In settings.py, add the new app:

1. Create the Model

Run the migrations:

2. Create Views

Create the view for the search functionality.

3. Create Templates

- Create a new folder called `templates` inside sim

- Add a file search.html inside templates:

Add a file search_results.html inside templates:

4. Update your urls.py

Include this in the project's main urls.py:

5. Time for testing - Add some entries to the database

Open your django shell from the terminal with:

Then in the shell:

Run the server.

Visit http://127.0.0.1:8000/search/ to see your instant search in action.


Congrats 🎉 Now here's a bonus to make it look better

  1. Add styling
  2. Highlight the matched text

1. Add styling to the html

2. Highlight the text matching your search query

  • Update your views.py to insert a span that highlights the matched text.

Finished

All done 🎉 You now know how to add instant search to Django 🐎 This is a simple type of search that's entirely unoptimised, but is great for starting.

My advice would be to avoid optimising your search completely until it starts to slow. I'd think about optimising only then to avoid premature optimisation (my wolf's bane).

P.S - Photon Designer

I'm building Photon Designer - an entirely visual editor for building Django frontend at the speed that light hits your eyes. Photon Designer outputs neat, clean Django templates.

Next:
How to create ChatGPT with Django and HTMX in 4 minutes 🦾

Let's get visual.

Do you want to create beautiful django frontends effortlessly?
Click below to book your spot on our early access mailing list (as well as early adopter prices).
Super ⭐️ Thanks for signing up and welcome! ✅
I'll send you a welcome email with some useful recent guides shortly

Check your spam or email me (tom@mail.photondesigner.com) if you don't receive it
📩
❌ Ah! Something something went wrong when signing up.

→ Email me at tom@mail.photondesigner.com and I'll sort it out for you 🙂