Search is a vital component of almost all web projects. Luckily Django has made it really easy to implement.

Kalle Tolonen
July 10, 2022
Let’s start by creating a new url in our urls.
#urls.py additions
from myproject import views
#SEARCH
path("search/", views.SearchResultsView.as_view(), name="search_results"),This will tell Django how it should react to a request (ie. what view will be called).
For the views, we only need to add a new listview.
#views.py in app folder
class SearchResultsView(ListView):
model = models.Article
template_name="mainsite/search_results.html"
def get_queryset(self):
query = self.request.GET.get("q")
object_list = models.Article.objects.filter(
Q(title__icontains=query) | Q(keywords__icontains=query)
)
return object_listTo make a query, we will override the stock queryset-method with our own. The default queryset will include all the items of the model in question from the database and it isn’t usable for searching as such.
Your models will be different and you’ll have to modify the provided code for your own purposes.
Few remarks:
1. model is the model from models.py 2. template_name is your template from the templates folder 3. get_queryset is the method we’re “taking over” 4. object_list is the result the method will return (and the one we can access from our template) 5. Q makes it possible to make complex queries
<h2 class="h2-title">Search results</h2><br>
{% for article in object_list %}
<a href="{{article.get_absolute_url}}" class="text-dark">{{ article.title }}</a>
{{ article.lead }}
<i>{{ article.created }}</i><br>
{% endfor %}Search requires input from the user, and to get that, we need a form.
<form action="{% url 'search_results' %}" method="get">
<input name="q" type="text" placeholder="Search...">
</form>Add the above to your desired html.
No published comments yet.
Your comment may be published.