How to Add Search Functionality to Django Applications

Adding a search feature to your web application lets your users navigate it easily by searching for what they want. Django provides built-in support for building a search feature by using its powerful ORM and query tools. With Django, you can implement different types of searches, including keyword searches, simple searches, and advanced searches with filters.

Implementing Search Functionality in Django

Django allows you to implement different types of searches with its built-in methods and functions. you may implement a simple keyword search or an advanced search based on your use case. You should implement an advanced search if you have a complex application, such as an e-commerce website, while a simple keyword search is suitable for less complex projects.

The code used in this article can be found onGitHuband is free for you to use under the MIT license.

4

Implement a Simple Keyword Search in Django

To create a simple search feature, you should start by building your search bar. You can build your search bar in your navbar.Bootstrapprovides a ready-made navbar with a search bar, and you can easilyintegrate Bootstrap and its components into your Django project. Create your search bar in an HTML file, set the form method toPOST,and give the input field anameattribute like this:

In the above code, the name of the input field issearch_query. The form makes use ofDjango’s CSRF tokentoprevent CSRF attacks. To make your search bar work, follow these steps.

iCloud+ Website on MacBook Sitting on Kitchen Island

The above function first checks if the client is sending aPOSTrequest. If the check passes, it goes ahead to retrieve the value of the user’s search query like this:

In request.POST[’search_query’],‘search_query’should be replaced with the name of your search bar’s input field.

The famous

After retrieving the value of the user’s search query, the function filters the model with it by using the__containsmethod. The__containsmethod is case-insensitive. To use this method, you should follow this format:

For example, if you want your users to search based on a model field calledname, you should modify your code to look like this:

USB-C port on the Google Pixel 8a

Finally, the function renders a template and passes the search query and filtered model as context.

However, if the form’s method is not aPOSTrequest, the function renders a template with an empty dictionary and does not process the search query.

Four search icons arranged around the wprd,

Create a Template for the Search Result

The above HTML template checks if the user enters a search query in the search bar. If the user enters a search query, afor looploops over the search results and returns them to the user. When there is no search query, a message is displayed for the user to enter a search query. A case where there might be no search query is if your user goes directly to the URL without filling in the search bar, i.e., your user enters a URL such asmywebsite.com/searchdirectly into the browser. You should ensure that you useDjango’s template inheritancein your HTML file.

The new HTML template allows for a better user experience. It introduces a conditional statement to check if a search result is available in the database. If there is, it displays the search result; otherwise, it sends the user an error message.

Configure Your URL Patterns

The program above first imports thepathfunction and theviewsfile related to the app. Then it creates a path namedsearch-viewfor the search page.

Without a form action pointing to your search URL path, your search feature will not work. Remember that your search URL path must point to the Django view that handles the logic of your search feature.

Create a Search Feature for Multiple Model Fields

If you want to improve the user experience of your web app, you can let your users search by more than one field in your model. For instance, in a blog app, you might want your user to search based on post titles or author names.

To implement this feature, you should use theQobject provided by Django. You should import theQobject in yourviews.pyfile like this:

After importingQ, you should modify your view function like this:

In the program above, thepostsvariable filters the model by either the post title or the author’s name. The function uses theORoperator—in this case, a pipe symbol—to perform the filter.

Improving User Experience With a Search Feature

A search feature in your web application effectively improves its user experience and overall usability. With Django, you only need to leverage the built-in functionalities to make your search feature work, providing significant benefits for you and your users.

Working with open source projects involves many skills, starting with cloning and setting up a project.

It saves me hours and keeps my sanity intact.

Freeing up vital memory on Windows only takes a moment, and your computer will feel much faster once you’re done.

Don’t let someone else take over your phone number.

My foolproof plan is to use Windows 10 until 2030, with the latest security updates.

My iPhone does it all, but I still need my dumb phone.

Technology Explained

PC & Mobile