HTMX + Django: Modern Python Web Apps, Hold the JavaScript Transcripts
Chapter: Feature 2: Active search
Lecture: Update the search view
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
It's time to remove the hardcoded text. Now instead I'm grabbing the search text out of the query parameters.
0:14
I'm using the get method on the getDict, so I can provide a default value of empty string.
0:22
If there isn't any query parameters, then the search text is assumed to be empty.
0:28
The search text is going to be URL encoded because, well, it was inside of a URL. Let's deal with that as well as any padding it might have.
0:48
Now search text should contain what's needed to build the query string.
0:52
I want to differentiate between a clean load of the page that is empty and a page that
0:57
has video results. In order to do that, I'm starting with videos as None. If it is None,
1:03
the result count won't be displayed because of the if clause. There's a chance there isn't
1:09
any search text, so I need to move this chunk into a block. Now, if there is search text,
1:20
the None value of videos will be replaced with search results. The last thing I need
1:25
to do is deal with the fact that this page can be called either in full mode or partial
1:30
mode. The Django HTMX library's middleware has added an HTMX member to the request, which,
1:37
when checked in Boolean context, reports true if the call is an HTMX call, and false otherwise.
1:54
Now the view can be used for the entire page or for the partials. If it is an htmx call, only the partial gets rendered.
2:03
And if it isn't, the original render is called, which displays the whole page. I'm almost ready to test this baby out.
2:12
URLlib hasn't been imported yet, so I need to add that at the top of the file. And here we go. Refreshed the home page, let's go back into search.
2:29
And as a clean page, there's no results to load. Let me type something. And as I type, things get filled in. And there's another one.
2:43
If I move the cursor around, nothing changes, so the HX Get doesn't get triggered. If I wipe this out, it clears.
2:53
Hmm, I'm not sure if I'm happy with that. A lot of search-as-you-type pages require you to type a few letters, as F could mean
3:03
every single result in our video archive. Let's do two last things.
3:09
First, require a minimum-sized search text, and second, to update the URL as you type.