Search code examples
pythondjangohttpsearchget

Load URL without Search Query


DJANGO/PYTHON I am trying to load http://127.0.0.1:8000/catalog/. If the user enters data into the on this page, the form sends a search_query to the database. My problem is that http://127.0.0.1:8000/catalog/ does not load – it leads to a 'MultiValueDictKeyError' exception type with exception value 'search_query'. However, when the user submits data into the form, (i.e. http://127.0.0.1:8000/catalog/?search_query=biography+of) the page loads. I am trying to make it so that http://127.0.0.1:8000/catalog/ loads without the user having to submit a search query.

Here is my view function:

def index(request):
   . . .
     num_of_word = []
     bookInstance_titles = []
     bookInstance_ids = []
     num_of_word = BookInstance.objects.filter(status='a',      book__title__contains=request.GET['search_query']).count()
bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET['search_query'])
     for i in bookInstances:
        bookInstance_titles.append(str(i.book))
        bookInstance_ids.append(str(i.id))

    context = {
    . . .
    'num_of_word': num_of_word,
    'bookInstance_titles': bookInstance_titles,
    'bookInstance_ids': bookInstance_ids,
}

I believe the problem is that the variables (num_of_word and bookInstances) are trying to access the request's search_query, yet the /catalog/ request does not have a search query. After research, I am still not sure how to solve this.

Thank you!


Solution

  • you try to access GET query when it doesn't exists. you must check if search_query exists in request.GET or simply use .get function on it. see below:

    def index(request):
         . . .
         num_of_word = []
         bookInstance_titles = []
         bookInstance_ids = []
         num_of_word = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', '').count()
         bookInstances = BookInstance.objects.filter(status='a', book__title__contains=request.GET.get('search_query', ''))
         for i in bookInstances:
             bookInstance_titles.append(str(i.book))
             bookInstance_ids.append(str(i.id))
        context = {
             . . .
             'num_of_word': num_of_word,
             'bookInstance_titles': bookInstance_titles,
             'bookInstance_ids': bookInstance_ids,
        }