0

I have a problem with my search bar in Django.

I create a simple view:

class BookList(ListView):
    model = Book

    def book_list(request):
        books = Book.objects.all()
        search_term = ''

        if 'search' in request.GET:
            search_term = request.GET['search']
            books = books.filter(text__incontains=search_term)

        context = {'books': books, 'search_term': search_term}

        return render(request, 'book_list.html', context)

And simple form:

<form class="form-inline my-2 my-lg-1">
   <input class="form-control mr-sm-2"
       type="search"
       placeholder="Search"
       aria-label="Search"
       name="search"
       value="{{ search_term }}">
   <button class="btn btn-outline-success my-2 my-sm-0" type="submit">search</button>
</form>

When I try to search something in my search bar, it was isn't working. I'm a newbie in Django and I don't know how to fix it.

Satendra
  • 6,755
  • 4
  • 26
  • 46

1 Answers1

0

Your code is not clear enough I guess you're using a CBV since you're using the variable name `object_list, and trying to retrieve GET parameter by implementing an FBV inside, it's totally not correct.

try the following:

class BookList(ListView):
    model = Book
    template_name = 'template.html'

    def get_queryset(self):
        books = self.model.objects.all()
        if 'search' in request.GET:
            search_term = request.GET['search']
            books = books.filter(text__incontains=search_term)
        return books

    def get(self,request, *arg,**args)
        context = self.get_context_data(**kwargs)
        context['search_term'] = request.GET.get('search','')
        return render(request.self.template_name,context)
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
  • It still doesn't work. When i click on the search button, it don't do anything. I placed this form in my base.html and book_list.html. – Sparrowekk Jun 10 '18 at 18:58
  • can you edit your code and post how your view looks like now? and how you loop through object_list – Lemayzeur Jun 10 '18 at 19:20
  • in this moment i have something like this: https://pastebin.com/JgvWgKPp When i go to my book list view in website i have this error: ValueError at /books/ Cannot use None as a query value – Sparrowekk Jun 11 '18 at 11:34
  • I fix it by adding a new SearchView in my views file. – Sparrowekk Jun 13 '18 at 10:13