How to create a search bar inside your django blog or website

Creating a search bar within your website is indeed a great way for users to navigate quickly on to a page they want to view. It provides an almost instant navigation to the desired page needed without having to comb around your website.

Django provides an easy link from your urls.py file to views.py, thus requesting for files searched for by your users like any search bar would work.

In creating a search feature, you will need to setup your urls.py inside your main django project. Like below;

URLS.PY

from django.contrib import admin
from appname import views
from django.urls import path


urlpatterns = [
    path('admin/', admin.site.urls),
    path('search/', views.search, name='search')
]

So from django.contrib we are importing the admin features for your django project. From 'your app' you have created we are importing views from it and also from django.urls we are importing path to map our urls to views. Thus as far as the code above states.

After doing all that what else do we do? We have to create a search function in our views.py (functional view, could also be a class based view) in this example we are using a functional view. Like below;

VIEWS.PY

def search(request):
    if request.method == 'POST':
        searched = request.POST['searched']
        search_results = Post.objects.filter(title__icontains=searched, status=1)

        return render(request,
                      'search.html',
                      {'searched': searched,
                       'search_results': search_results})

    else:
        return render(request, 'search.html')

The code above simply states, from;

  1. Line one we have defined our view and named it 'search'. Thus matching with our urls.py name also being 'search'
  2. On line two we are making an if statement; (if a condition), that is if the method in our html file template is equal to 'post' then we want a series of actions to take place
  3. On line 3 we have also stated that the name of the form 'searched' if a user enters a query inside the search bar we want it stored inside the variable 'searched' for further action . INSIDE OUR TEMPLATE HTML - AS SHOWN BELOW
    <input name="searched" type="search" class="search-field" placeholder="Search...">

     

  4. Line 4 shows 'searched' (words entered by user) being queried against all the 'objects' and if any such object(s) matches with the user's inputs that has been published (status=1) then,
  5. We want to return a page to display the filtered items, the keyword and the results.
  6. If not then the function should just display the page and do nothing.

I hope this simple feature will help you setup your search bar functionality inside your blog or website without hussle.

If you need assistance with your projects feel free to email me at info@airgad.com or whatsapp Jesse stay safe!