How to Use Search Filter in Django?

Published On: 02/01/2023 | Category: Django


Hi Dev,

Now, let's see post of how to use search filter in django. if you want to see example of django search example tutorial then you are a right place. you will learn django search filter example. I would like to share with you how to implement search in django.

Here i will give you we will help you to give example of django search example. So let's see the bellow example:

Step 1: Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2: Create a App
cd example
django-admin startapp core

Step 3: Update settings.py

Next, you need to add it in the settings.py file as follows:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'core', #new
] 
Step 4: Create a Model

Now go for the models we will We'll call our single model Lead and it will have just two fields: name, email and message. And finally set __str__ to display the name of the lead in admin interface.

core/models.py
from django.db import models

# Create your models here.
class Lead(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField(max_length=100, unique=True)
    message = models.CharField(max_length=500)

    def __str__(self):
        return self.name

Ok, all set. We can engender a migrations file for this change, then integrate it to our database via migrate.

python manage.py makemigrations
python manage.py migrate

Step 5: Update admin.py file

In this step, we need to configure admin file. open the core/admin.py file and add:

core/views.py
from django.contrib import admin
from .models import Lead

# Register your models here.
admin.site.register(Lead)
Output

So, add the record in our lead model manually..



Step 6: Creating the Views

In this step, we need to configure views. open the core/views.py file and add:

core/views.py
from django.shortcuts import render
from .models import Lead
from django.db.models import Q
from django.views.generic import ListView

# Create your views here.
class SearchResultsView(ListView):
    model = Lead
    template_name = "search.html"

    def get_queryset(self):  # new
        query = self.request.GET.get("q",None)

        if query:
            object_list = Lead.objects.filter(
                Q(name__icontains=query) | Q(email__icontains=query)
            )
        else:
            object_list = Lead.objects.all()
        return object_list

Step 7: Creating the Templates

Here, in this step we need to create a new folder named core in the templates folder of core.

core/templates/search.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css">
    <style type="text/css">
        body{
            background-color: #f7fcff;
        }
    </style>
</head>
<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-md-9">
                <div class="card">
                    <div class="card-header">
                        <h3>How to Use Search Filter in Django? - <span class="text-primary">Tuts-Station.com</span></h3>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <ul>
                              {% for lead in object_list %}
                                <li>
                                  {{ lead.name }}, {{ lead.email }}
                                </li>
                              {% endfor %}
                            </ul>
                        </div>
                        <form action="{% url 'search' %}" method="get">
                            <input name="q" type="text" class="form-control" placeholder="Search...">  
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

Step 8: Creating URLs

In this section, we need a urls.py file within the core app however Django doesn't create one for us with the startapp command. Create core/urls.py with your text editor and paste below code.

core/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('search', views.SearchResultsView.as_view(), name="search"),
]

Next, we require to add a URL path for our example app which can be done by importing include and setting a path for it.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('core.urls')),
]

Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

I Hope It will help you....