0
0
Djangoframework~30 mins

Filtering with django-filter - Mini Project: Build & Apply

Choose your learning style9 modes available
Filtering with django-filter
📖 Scenario: You are building a simple web app to display a list of books. Users want to filter books by their genre.
🎯 Goal: Create a Django view that uses django-filter to filter books by genre and display the filtered list.
📋 What You'll Learn
Create a Django model called Book with fields title and genre
Create a filter class called BookFilter using django_filters.FilterSet to filter by genre
Create a view called book_list that applies BookFilter to the Book queryset
Render the filtered books in a template
💡 Why This Matters
🌍 Real World
Filtering data is common in web apps to help users find what they want quickly, like filtering products by category.
💼 Career
Knowing django-filter helps you build user-friendly Django apps that handle data filtering efficiently, a valuable skill for backend and full-stack developers.
Progress0 / 4 steps
1
Create the Book model
Create a Django model called Book with two fields: title as CharField with max length 100, and genre as CharField with max length 50.
Django
Need a hint?

Use models.CharField for both fields with the specified max lengths.

2
Create the BookFilter class
Create a filter class called BookFilter that inherits from django_filters.FilterSet. Inside, create a Meta class that sets model = Book and fields = ['genre'].
Django
Need a hint?

Import django_filters and create a class that inherits from django_filters.FilterSet.

3
Create the book_list view
Create a Django view function called book_list that takes request as a parameter. Inside, create a BookFilter instance called book_filter using request.GET and Book.objects.all(). Then get the filtered queryset as books = book_filter.qs.
Django
Need a hint?

Import render from django.shortcuts. Use BookFilter(request.GET, queryset=Book.objects.all()) to filter.

4
Add the filter form to the template
In the template book_list.html, add the filter form by including {{ filter.form.as_p }} inside a <form> with method get. Below the form, loop over books and display each book's title and genre inside <li> tags.
Django
Need a hint?

Use a <form method="get"> with {{ filter.form.as_p }} and a submit button. Loop over books with {% for book in books %}.