需要在基于 Django class 的视图上添加搜索功能

Need to add a search functionality on Django class based view

我在基于函数的视图上有一个搜索功能,效果很好。 这是基于函数的视图代码:

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})

但现在我想通过在这个基于class的视图上实现它来替换那个基于函数的视图

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

这是我的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 搜索功能部分:

<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>
      </form>

由于我是新手,尝试了不同的解决方案,但都没有解决。如果有人帮助我,我会很高兴。

您可以覆盖 ListView 中的 get_queryset 方法。

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
</pre>
		

可以有很多搜索功能,例如, 按作者搜索,blog_title..

正在回答 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})