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

Hi, I'm John, a Software Engineer with a decade of experience building, deploying, and maintaining cloud-native geospatial solutions. I currently serve as a senior software engineer at New Light Technologies (NLT), where I work on a variety of infrastructure and application development projects.

Throughout my career, I've built applications on platforms like Esri and Mapbox while also leveraging open-source GIS technologies such as OpenLayers, GeoServer, and GDAL. This blog is where I share useful articles with the GeoDev community. Check out my portfolio to see my latest work!