๐ 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
kacan matchKavita - searching
mcacan matchMCA
๐ฏ Program Statement
๐ Implement search functionality using icontains.
๐ง Concept
This program uses:
- model data
- GET form for search input
filter()withicontains- 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 URLStudent.objects.all()loads all records initiallyfilter(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
- User opens search page
- Enters text in search box
- Form sends query using GET method
- View receives query
icontainsfilters records- 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
- Search by course instead of name
- Search by email
- Search by both name and course
- Show total number of matching records
- 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
Examples of Array Functions in PHP
Registration Form Using PDO in PHP
Inserting Information from Multiple CheckBox Selection in a Database Table in PHP
- Angular
- ASP.NET
- C
- C#
- C++
- CSS
- Dot Net Framework
- HTML
- IoT
- Java
- JavaScript
- Kotlin
- PHP
- Power Bi
- Python
- Scratch 3.0
- TypeScript
- VB.NET
