Excited to implement search functionality to the site. This will be helpful in the future when there are a lot more posts and anyone wants to find posts that contain specific content.

I first grabbed a search toolbar from the bootstrap website which basically entailed looking through the navbars and yanking out the search functionality. When I initially implemented the navbar, I actually removed the default search because I wasn't ready to work on it, so I guess I am just putting it back!

Next up was wiring up the search button to make a POST request to the 'blog-search' url. Once it hit urls.py, the request is sent to the SearchView which does most of the work.

Found a useful Youtube Video for creating search functionality, but it's limited in that you can only search one field in the Post model. I wanted users to search both the title of a post AND the content of the post. The final view looked like this:

def SearchView(request):
    """Controls what is shown to a user when they search for a post."""
    cat_list = Category.objects.all()
    if request.method == 'POST':
        searched = request.POST['searched']
        filtered_posts = Post.objects.filter(Q(content__icontains=searched) | Q(title__icontains=searched))
        return render(
            request,
            "blog/search_posts.html",
            {"cat_list": cat_list, "searched": searched, "filtered_posts": filtered_posts},
        )
    else:
        return render(
            request,
            "blog/search_posts.html",
            {"cat_list": cat_list},
        )

One line 194 you can see the implementation from the Youtube Video, but I went a step further. After reviewing the ckeditor docs, I came across functionality called 'Q' which allows you to manufacture more complex queries. You can accomplish the equivalent of an 'OR' in SQL using the pipe character. In my case, it is searching and returning posts that contain the search query in either the content of the post OR the post's title.

I might look into adding more search functionality (like a date filter or searching Comment text)...but I am pretty happy with how it works for now. 

Comments

Back to Home
John Solly Profile Picture
John Solly Profile Picture

John Solly

A hands-on AI practitioner who transitioned to a CTO role to broaden my impact.

Most of my career has been dedicated to developing spatial systems at Esri, startups, and federal agencies. Currently, I lead technology strategy for Leidos' Health IT division, supporting agencies such as SSA, VA, and HHS.

My primary focus is the convergence of spatial computing and AI, enabling machines to interpret the physical world and applying these capabilities to meaningful missions.

Please reach out if you are interested in spatial systems or advancing AI within the federal government.