How To Implement Search In Django


If you have created blog or ecommerce application, you will try to design your template in such a way that will help users find required options very easily. However you can not put links for everything. It will make user experience very bad, and user may not be able to find what they need. Best way to help your users find what they need is to implement search feature. ## Step#1 Create a search form You need to show a search box on your webpage where user can type a keyword to search. Here is sample search box. ```html <div class="p-3"> <form class="input-group" action="/search" method="get"> <input class="form-control width100" name="searchterm" type="text" placeholder="Search..."> <span class="input-group-btn"> <button class="btn btn-primary">Search</button> </span> </form> ``` Please note the `name='searchterm'` parameter of input. Once keyword has been submitted on webpage, django need to process it. To process it, let is create a URL for search. ## Step#2 create URL structure to search You need to add following line in `app/urls.py` ```python path('search/',views.search, name='search'), ``` ## Step#3 Search in your database This is where actual search happens, you need to capture keywork using URL parameter. To learn more about passing variable from template to view, please read post [How To Pass Variable From Template To Views In Django](https://techtrekking.com/how-to-pass-variable-from-template-to-views-in-django/) . Add followiing function in `view.py` ```python def search(request): searchterm = request.GET.get('searchterm') context = YourModelName.objects.filter(ColumnToSearch__contains=keyword).order_by('-dt') return render(request, 'blog/index.html',{'context':context}) ``` Please note, first we are getting keyword into a variable called as "searchterm". Please note, this variable name is not any random vriable, this is the `name` attribute of input in the form. Also, note the query, here we are using `__contains`. You can also use `__icontains` without any major change in above code. In fact `__icontains` is preferred between two. For more advance usage, you can use `search` , `SearchVector` , `SearchQuery` or `SearchRank`. Please refer to [documentation here](https://docs.djangoproject.com/en/4.0/ref/contrib/postgres/search/). ## Step#4 Display search output in required way Here is usual process of passing QuerySet output to template. To displya output, just loop thru the variable and display, required attributes. ```html {% for post in context %} <h4><a href="/{{post.title_slug}}">{{ post.title_name}}</a></h4> <p>by {{ post.author_name}} </p> {% endfor %} ``` Hope this is helpful...

This post is written by Pravin

Tags : Django

Share it :      

Leave a comment

captcha