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 manage.py migrate

(.venv) > python manage.py runserver

 

 

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

python manage.py startapp cities

 

Then update INSTALLED_APPS in settings.py file 

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

 

Then create model in models.py 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 self.name

 

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

And run below command.

 

python manage.py makemigrations citiespython manage.py migratepython manage.py createsuperuser 

 

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

 

from django.contrib import admin 

from .models import City 

class CityAdmin(admin.ModelAdmin): 

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

admin.site.register(City, 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/", admin.site.urls),    

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

]

 

 

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

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 settings.py 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.name }}, {{ city.state }}  </li>

  {% endfor %}

</ul>

 

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

<h1>HomePage</h1> 

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

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

</form>

after creating all above function again you can run command 

python manage.py runserver

 

 

 

 

 

 

 

--Posted By : santosh


Back to Post
Comments....

All Comments...

No comments yet !!!!

Bestsaller

Online Store


Populer Store
Electronics Store
Services Store
Other Services