Home > Software engineering >  Need to add a search functionality on Django class based view
Need to add a search functionality on Django class based view

Time:01-03

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 models.py:

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  method="GET">
        <input  type="text" name="search" placeholder="Search the topic">
        <button  type="submit">Search</button>
      </form>

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.

CodePudding user response:

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

CodePudding user response:

There can be many search functionalities like, Search by author, blog_title..

Answering for search by blog_title,

def search(request):
    title_to_search_by = request.GET.get('search')
    blogs_searched = Blog.objects.filter(blog_title__icontains=title_to_search_by)
    return render(request, 'yourTemplate.html' , {'search_results', blogs_searched})
  • Related