How to activate search using Django and Django-filter

Emmanuel Onwuegbusi
3 min readNov 2, 2020

--

Photo by Kevin Ku on Unsplash

In this tutorial, we are going to learn how to build a simple search system using django and 'django_filter' which allows users to filter down a queryset based on their required search.

Our final project will be like this:

search app interface

We will be able to search for a pet in the search option and 'django_filter' will take our written text to perform a filter to give us our required result.

Let’s get in

Install django-filter

First, suppose we have our project and app as searchProject, searchapp respectively. We have to install 'django_filters' to our project.

install 'django_filter':

pip install django-filter

Then add 'django_filter' to your INSTALLED_APPS

INSTALLED_APPS = [
...
'django_filters',
]

The model

from django.db import models


class Pet(models.Model):
image = models.ImageField(upload_to='pet')
pet_name = models.CharField(max_length=200)

def __str__(self):
return self.pet_name

We will use the pet_name field from our model to perform our query.

The filter

Create filters.py in searchapp or our app directory, then add the following code

import django_filters
from .models import Pet
from django_filters import CharFilter


class PetFilter(django_filters.FilterSet):
pet_name = CharFilter(field_name='pet_name',
lookup_expr='icontains')

class Meta:
model = Pet
fields = ['pet_name']

This creates a FilterSet to allow us to filter by pet_name and lookup_expr ensures that letters typed are case-insensitive. ‘As you can see this uses a very similar API to Django’s ModelForm. Just likeModelForm we can also override filters, or add new ones using a declarative syntax’.

The view

from django.shortcuts import render
from .models import Pet
from .filters import PetFilter


# Create your views here.
def index(request):
myFilter = PetFilter(request.GET, queryset=Pet.objects.all())
pets = myFilter.qs

context = {
'pets': pets,
}
return render(request, 'projx.html', context)

Our index function will filter based on the parameter passed from the form or search option on the HTML page. ‘If a queryset argument isn’t provided then all the items in the default manager of the model will be used’.

If you want to access the filtered objects in your templates call the variable pets

The URL conf

copy and paste this code to the urls.py file of your application

from django.urls import path
from .views import index

from django.contrib.auth import views as auth_views

urlpatterns = [
path('', index, name='index'),
]

The template

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<link rel="stylesheet" href="styles.css">
</head>

<body>
<div class="container">
<h3>Search in Django</h3>

<!-- Search form -->
<form action="" method="get">
<input class="form-control" name="pet_name" type="text" placeholder="Search Pets" aria-label="Search">
<br>
<button type="submit" class="btn btn-primary">Search</button>
</form>
<br><br>

<div class="row">
<div class="col-12">
<table class="table table-image">
<thead>
<tr>
<th scope="col">Image</th>
<th scope="col">Pet</th>
</tr>
</thead>
<tbody>
<!-- searchresult -->
{% for pet in pets %}
<tr>
<td class="w-25">
<img src="{{pet.image.url}}" class="img-fluid img-thumbnail" alt="Sheep" width="200" height="10">
</td>
<td>{{pet.pet_name}}</td>
</tr>
{% endfor %}


</tbody>
</table>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

The search form performs the search and searchresult show the result from the database. And that’s all there is to it!

Follow me on twitter: @emmakodes

linkedin: https://www.linkedin.com/in/emmanuelonwuegbusi/

Conclusion

Hopefully, this tutorial gave you some insights on how to use 'django_filters'. As always, the official documentation is the best source of information:

https://django-filter.readthedocs.io/en/stable/index.html

Also, the code used in this tutorial is available on GitHub at https://github.com/emmakodes/searchProject

--

--

Emmanuel Onwuegbusi
Emmanuel Onwuegbusi

Written by Emmanuel Onwuegbusi

Software Developer | Machine Learning

No responses yet