DEV Community

Cover image for Django Tutorial #8: Search

Django Tutorial #8: Search

ericnanhu profile image Eric Hu Originally published at ・2 min read

You can download the source code of this tutorial here.

The search function is a fundamental feature for almost all websites, and in this article, we’ll talk about how to implement basic search in our Django project.

A search function consists of three parts, a search form that allows users to pass queries to the back end, a piece of code that does the search, and a template that displays the results of the search.

Search Form

Now, let’s add a search form into our sidebar:

<!-- Search Widget -->
<div class="card my-4">
    <h5 class="card-header">Search</h5>
    <form class="card-body" action="{% url 'search' %}" method="GET" role="search">
        <div class="input-group">
                <input type="text" class="form-control" placeholder="Search for..." name="q">
            <span class="input-group-btn">
            <button class="btn btn-secondary" type="submit">Go!</button>
Enter fullscreen mode Exit fullscreen mode

Line 7, adds name attribute to the input field, its value could be anything, here we’ll call it q.

When the button is clicked, it’ll go to /search, so we need to register the corresponding URL pattern.

path('search',, name='search'),
Enter fullscreen mode Exit fullscreen mode

Search View

def search(request):
    general = General.objects.first()
    query = request.GET.get('q', '')
    if query:
        posts = Post.objects.filter(title__icontains=query)
        posts = []
    return render(request, 'blog/search.html', {
        'general': general,
        'posts': posts,
        'query': query,
Enter fullscreen mode Exit fullscreen mode

Line 3, this line of code will get whatever is in that input box and assign it to query.

Line 5, This will get a group of posts whose title contains query. There are a lot more lookup methods other than contains:

Search Template

{% extends "blog/master.html" %}

{% block meta %}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="{{ general.description }}">
    <meta name="author" content="">

{% endblock %}

{% block content %}

    <!-- Page Content -->
    <div class="container">
        <div class="row">
            <!-- Blog Entries Column -->
            <div class="col-md-8">
                <h1 class="my-4">Search Result For:
                    <small>{{ query }}</small>
                {% include 'blog/vendor/post_list.html' %}
            {% include 'blog/vendor/sidebar.html' %}
        <!-- /.row -->
    <!-- /.container -->

{% endblock %}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Forem Open with the Forem app