Need to add a search functionality on Django class based view

I have a search function on a function based view that works fine. This is the function based view code:

def BlogList(request):
blogs = Blog.objects.all()
if request.method == 'GET':
    search = request.GET.get('search', '')
    blogs = Blog.objects.filter(blog_title__icontains=search)
return render(request, 'App_Blog/blog_list.html', context={'search':search, 'blogs':blogs})

But now I want to replace that function based view by implementing it on this class based view.

class BlogList(ListView):
context_object_name = 'blogs'
model = Blog
template_name = 'App_Blog/blog_list.html'

This is my

class Blog(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='post_author')
blog_title = models.CharField(max_length=264, verbose_name="Put a Title")
slug = models.SlugField(max_length=264, unique=True)
blog_content = models.TextField(verbose_name="What is on your mind?")
blog_image = models.ImageField(upload_to='blog_images', verbose_name="Image")
publish_date = models.DateTimeField(auto_now_add=True)
update_date = models.DateTimeField(auto_now=True)

class Meta:
    ordering = ['-publish_date',]

def __str__(self):
    return self.blog_title

html part for search function:

<form class="form-inline ml-auto" method="GET">
        <input class="form-control mr-sm-2" type="text" name="search" placeholder="Search the topic">
        <button class="btn btn-success" type="submit">Search</button>

As I am a newbie, I have tried different solutions but not getting it through. I’ll be glad if someone help me on this.


You can override the get_queryset method inside your ListView.

class BlogList(ListView):
    context_object_name = 'blogs'
    model = Blog
    template_name = 'App_Blog/blog_list.html'

    def get_queryset(self):
        search = self.request.GET.get('search', '') 
        blogs = Blog.objects.filter(blog_title__icontains=search)
        return blogs