Create Search Function Django

Educations 3 Fri 15 Jul 2022
Create Search …

Here we will create basic search function in  Django website and touch upon ways to improve it with more advanced options.

To start  creating a new Django I did it in a directory called search. At the command line, type the following command to install the latest version of Django, create a project called Citysearch_project and set up the initial database with migration, then start the local web server with runserver.

(.venv) > python -m pip install django

(.venv) > django-admin startproject citysearch_project .

(.venv) > python migrate

(.venv) > python runserver



Create a single app name of cities to store a list of city names

python startapp cities


Then update INSTALLED_APPS in file 

INSTALLED_APPS = [    ...    "cities",  # new]


Then create model in file and set __str__ to display the name of the city

from django.db import models 

class City(models.Model):    

name = models.CharField(max_length=255)    

state = models.CharField(max_length=255)    

  def __str__(self):        return


Then We can create a migrations file for this change, then add it to our database via migrate.

And run below command.


python makemigrations citiespython migratepython createsuperuser 


Now we have to update cities app in to display our app within the admin


from django.contrib import admin 

from .models import City 

class CityAdmin(admin.ModelAdmin): 

 list_display = ("name", "state",), CityAdmin)



We have a populated database, but there are still a few steps to take before it appears on our Django website. 

In the end, we only need the home page and the search results page. Each page requires a separate view, URL, and template The order in which we create them doesn't really matter; Everything must be there for the website to work. I usually like to start with a URL, add a view, and complete the template, so we'll do that here.


First, we need to add the URL path for the City app, which can be imported and set

from django.contrib import adminfrom django.urls import path, include # new 

urlpatterns = [    path("admin/",,    

path("", include("cities.urls")),




Second, we have need a file with in the cities mention app however Django doesn't create one for us with the startapp command. Create cities/

In this file we have import views file


from django.urls import path 

from .views import HomePageView, SearchResultsView 

urlpatterns = [    

path("search/", SearchResultsView.as_view(), name="search_results"),  

 path("", HomePageView.as_view(), name="home"),




Third, here we have  configure two views. 1st homepage will just be a template with, eventually, a search box. Django's TemplateView works nicely for that. The search results page will list the results you want which is a good fit for ListView.


from django.views.generic import TemplateView, ListView 

from .models import City  

class HomePageView(TemplateView):    

template_name = 'home.html' 

class SearchResultsView(ListView):    

model = City  

template_name = 'search_results.html'



lastly  we have need a templates. i can add the template with in our app but I find that creating a project level template folder


Then again update our file to tell Django to look for this project level templates folder. This can be found in the TEMPLATES section.

TEMPLATES = [    {        ...        "DIRS": [BASE_DIR / "templates"],   }]


Now create two new templates files: templates/home.html and templates/search_results.html


templates/home.html for HomePagetemplates/search_results.html  for search result 


<h1>Search Results</h1> 

<ul>  {% for city in object_list %}  

 <li>      {{ }}, {{ city.state }}  </li>

  {% endfor %}



Create Basic Filter for search

class SearchResultsView(ListView):   

model = City   

template_name = 'search_results.html'   

queryset = City.objects.filter(name__icontains='Boston') 



then create search result view


class SearchResultsView(ListView):    

model = City    

template_name = 'search_results.html'     

def get_queryset(self):   

 return City.objects.filter(name__icontains='Boston')

San Diego

in home page create search form


<form action="{% url 'search_results' %}" method="get">

 <input name="q" type="text" placeholder="Search...">


after creating all above function again you can run command 

python runserver








--Posted By : santosh

Back to Post

All Comments...

No comments yet !!!!


Online Store

Populer Store
Electronics Store
Services Store
Other Services