Django

Implement Search Functionality using icontains

๐Ÿ“Œ Introduction

Search is one of the most useful features in web applications.
It helps users find records quickly by entering a keyword.

In Django, search can be implemented using:

field__icontains=value

icontains means:

  • checks whether a field contains the given text
  • ignores uppercase/lowercase differences

For example:

  • searching ka can match Kavita
  • searching mca can match MCA

๐ŸŽฏ Program Statement

๐Ÿ‘‰ Implement search functionality using icontains.


๐Ÿง  Concept

This program uses:

  • model data
  • GET form for search input
  • filter() with icontains
  • dynamic display of results

โš™๏ธ Step 1: Model Used

We use the same Student model.

๐Ÿ“ File: models.py

๐Ÿ”น Path:

myproject/myapp/models.py

๐Ÿ”น Code:

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
course = models.CharField(max_length=100)
email = models.EmailField(unique=True)

def __str__(self):
return self.name

โš™๏ธ Step 2: Create Search View

๐Ÿ“ File: views.py

๐Ÿ”น Path:

myproject/myapp/views.py

๐Ÿ”น Code:

from django.shortcuts import render
from .models import Student

def search_student(request):
query = request.GET.get('q')
students = Student.objects.all()

if query:
students = Student.objects.filter(name__icontains=query)

return render(request, 'search_student.html', {
'students': students,
'query': query
})

๐Ÿง  Explanation

  • request.GET.get('q') gets the search text from URL
  • Student.objects.all() loads all records initially
  • filter(name__icontains=query) searches names containing the text
  • results are passed to template

โš™๏ธ Step 3: URL Mapping

๐Ÿ“ File: urls.py

๐Ÿ”น Path:

myproject/myproject/urls.py

๐Ÿ”น Code:

from django.contrib import admin
from django.urls import path
from myapp import views

urlpatterns = [
path('admin/', admin.site.urls),
path('search-student/', views.search_student, name='search_student'),
]

โš™๏ธ Step 4: Create Template

๐Ÿ“ File: search_student.html

๐Ÿ”น Path:

myproject/templates/search_student.html

๐Ÿ”น Code:

<!DOCTYPE html>
<html>
<head>
<title>Search Student</title>
</head>
<body>

<h1>Search Student</h1>

<form method="get">
<input type="text" name="q" placeholder="Enter student name" value="{{ query|default:'' }}">
<button type="submit">Search</button>
</form>

<hr>

{% if query %}
<h2>Search Results for "{{ query }}"</h2>
{% else %}
<h2>All Student Records</h2>
{% endif %}

{% if students %}
<ul>
{% for s in students %}
<li>
{{ s.name }} | {{ s.course }} | {{ s.email }}
</li>
{% endfor %}
</ul>
{% else %}
<p>No matching records found.</p>
{% endif %}

</body>
</html>

๐Ÿง  Explanation

  • form uses method="get" because search data is usually passed in URL
  • value="{{ query|default:'' }}" keeps the searched text in the input box
  • results are shown dynamically
  • if no matching record exists, a message is displayed

โš™๏ธ Step 5: Run Server

python manage.py runserver

๐ŸŒ Step 6: Output

Open:

๐Ÿ‘‰ http://127.0.0.1:8000/search-student/

โœ… Without search text:

All student records are displayed.

โœ… Example Search:

Search text:

ka

โœ… Matching Output:

Kanchan | MCA | kanchan@example.com

โœ… Another Search:

Search text:

aman

Output:

Aman | BCA | aman@example.com

โŒ If no record matches:

No matching records found.

๐Ÿง  How It Works

  1. User opens search page
  2. Enters text in search box
  3. Form sends query using GET method
  4. View receives query
  5. icontains filters records
  6. Matching results are displayed

๐Ÿ”ฅ Key Concepts

Get Search Value

query = request.GET.get('q')

Gets the search term from URL.


Filter Records

Student.objects.filter(name__icontains=query)

Searches records where name contains the query text.


icontains

name__icontains=query

Case-insensitive contains search.


Display Query in Box

value="{{ query|default:'' }}"

Keeps search term visible after submission.


โš ๏ธ Common Errors

โŒ Using contains instead of icontains

contains is case-sensitive, while icontains ignores case.


โŒ Wrong parameter name

If input name is:

name="q"

then view must use:

request.GET.get('q')

โŒ Search not working on multiple fields

Current code searches only name.
If you want to search course or email too, you need more conditions.


โŒ GET form missing value retention

Without:

value="{{ query|default:'' }}"

the search box becomes empty after search.


โŒ No records in database

If table has no data, nothing meaningful will appear.


๐Ÿงช Practice Questions

  1. Search by course instead of name
  2. Search by email
  3. Search by both name and course
  4. Show total number of matching records
  5. Display results in table format instead of list

๐ŸŽค Viva Questions & Answers

1. What is icontains in Django?

icontains is a lookup used with filter() to search records containing a specific text without considering case differences.

2. What is the difference between contains and icontains?

contains is case-sensitive, while icontains is case-insensitive.

3. Why is GET method used in search forms?

GET method is commonly used for search because the search text appears in the URL and can be bookmarked or shared.

4. What is request.GET.get('q')?

It retrieves the value of the search input field named q from the URL query string.

5. What does filter() do in Django ORM?

filter() returns records that match the given condition.

6. Why do we use if query in the view?

It checks whether the user has entered any search text. If not, all records can be shown by default.

7. Can icontains be used on any text field?

Yes, it is commonly used with CharField, TextField, and similar text-based fields.

8. What happens if no record matches the search?

The QuerySet becomes empty, and the template can show a message like โ€œNo matching records found.โ€

9. Can we search more than one field?

Yes, Django allows multi-field searching using Q objects or multiple filter conditions.

10. Why is search functionality important?

It improves usability by allowing users to quickly find specific records from large datasets.


๐Ÿ”— Navigation

๐Ÿ‘‰ Next Post: Implement Pagination for Listing Records
๐Ÿ‘‰ Back to List: Django Programs (60 Questions with Solutions)


Further Reading

Introduction to Django Framework and its Features

Django Practice Exercise

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

Inserting Information from Multiple CheckBox Selection in a Database Table in PHP

programmingempire

princites.com

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *