📖 Scenario: You are building a simple Django web page to show a list of books. Users want to search for books by title and filter them by genre.
🎯 Goal: Create a Django view and template that display a list of books. Add a search box to find books by title and a dropdown to filter books by genre.
📋 What You'll Learn
Create a list of book dictionaries with title and genre
Add a variable to hold the search keyword
Filter the books list by the search keyword and selected genre
Render the filtered books in a Django template with a search form
💡 Why This Matters
🌍 Real World
Search and filter features are common in websites and apps to help users find content quickly and easily.
💼 Career
Understanding how to implement search and filter options in Django is a key skill for web developers building user-friendly interfaces.
Progress0 / 4 steps
1
Create the initial books data
Create a list called books with these exact dictionaries: {'title': 'Django for Beginners', 'genre': 'Programming'}, {'title': 'Cooking 101', 'genre': 'Cooking'}, {'title': 'Python Tricks', 'genre': 'Programming'}, {'title': 'Gardening Basics', 'genre': 'Hobby'}.
Django
Hint
Use a Python list with dictionaries. Each dictionary has keys 'title' and 'genre'.
2
Add search and filter variables
Create two variables: search_query set to an empty string '', and selected_genre set to 'All'.
Django
Hint
Set search_query to an empty string and selected_genre to the string 'All'.
3
Filter books by search and genre
Create a list called filtered_books that includes books from books where the search_query is in the book's title (case insensitive) and the book's genre matches selected_genre or selected_genre is 'All'. Use a list comprehension.
Django
Hint
Use a list comprehension with conditions for title containing search_query and genre matching selected_genre or 'All'.
4
Render filtered books in Django template
In a Django template, create a form with a text input named search_query and a select dropdown named selected_genre with options 'All', 'Programming', 'Cooking', and 'Hobby'. Below the form, use a for loop over filtered_books to display each book's title and genre inside <li> tags.
Django
Hint
Use a GET form with input and select elements named exactly search_query and selected_genre. Loop over filtered_books with Django template tags.
Practice
(1/5)
1. What does the Django ORM method filter() do when used with icontains in a query?
easy
A. It returns records where the specified field contains the given substring, case-insensitive.
B. It deletes records that contain the given substring in the specified field.
C. It updates records to include the given substring in the specified field.
D. It sorts records alphabetically based on the specified field.
Solution
Step 1: Understand filter() usage
The filter() method in Django ORM is used to select records that match certain conditions.
Step 2: Understand icontains lookup
icontains checks if a field contains a substring, ignoring case differences.
Final Answer:
It returns records where the specified field contains the given substring, case-insensitive. -> Option A
A. Using request.GET['search'] causes a syntax error.
B. The field lookup should use double underscores: name__icontains.
C. The filter method should be get() instead of filter().
D. The render function is missing the request parameter.
Solution
Step 1: Check field lookup syntax in filter()
The code uses name_icontains, but Django requires double underscores between field and lookup: name__icontains.
Step 2: Verify other parts of the code
Using request.GET['search'] is valid but may raise KeyError if missing; render() usage is correct with request parameter.
Final Answer:
The field lookup should use double underscores: name__icontains. -> Option B
Quick Check:
Field lookup syntax requires double underscores [OK]
Hint: Use double underscores for lookups like __icontains [OK]
Common Mistakes:
Using single underscore in field lookups
Confusing filter() with get()
Forgetting to pass request to render()
Assuming request.GET[] never raises errors
5. You want to build a Django view that filters Article objects by a search term in the title and also filters by a minimum number of views provided by the user. Which of the following code snippets correctly applies both filters using values from request.GET?
hard
A. query = request.GET['q']
min_views = request.GET['min_views']
articles = Article.objects.filter(title__icontains=query).filter(views__lte=min_views)
Using get() with default values avoids errors. Converting min_views to int is necessary for numeric comparison.
Step 2: Apply combined filters correctly
Using filter() with multiple conditions joined by commas applies AND logic. title__icontains=query and views__gte=min_views correctly filter by title substring and minimum views.