Abu Yunus
Abu Yunus

Reputation: 23

Search in Class Based ListView | Django

I am trying to search items in cbv. Though it's too easy with function based views but I don't know how to use it in CBV.

I tried like this

views.py

class HomeView(ListView):
    model = Item

    #query = request.GET.get("q")

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        query = self.request.GET.get('q')
        if query:
            context['model'] = Item.objects.get(title=query)
            print(query)
        return context

    paginate_by = 5
    template_name = "home.html"

home.html

<form class="form-inline my-2 my-lg-0" method="GET" action="">
 <input class="form-control mr-sm-2" type="text" name="q" placeholder="Search" value="{{ request.GET.q }}">
</form>

The problem is it's showing all items( not specifically searched items ). Example: in url http://127.0.0.1:8000/?q=Blue it is not only showing the item with Blue title but all items.

Upvotes: 1

Views: 1703

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You override the .get_queryset(…) method [Django-doc] to filter the objects:

class HomeView(ListView):
    model = Item
    paginate_by = 5
    template_name = 'home.html'

    def get_queryset(self, *args, **kwargs):
        qs = super().get_queryset(*args, **kwargs)
        query = self.request.GET.get('q')
        if query:
            return qs.filter(title=query)
        return qs

This queryset will then be paginated as well. So that means that in this case, it will show the first five matches.

Upvotes: 1

Related Questions