0

I submit a form with two inputs to search a table. My code doesn't get the value of 'namequery' instead of displaying all data in table. What did I do wrong here? Thanks for any help! The url is http://..../chinook/search/?namequery=rand&affquery=

search.html

  <h3 class="labs-background-title">Search results for <em id="search-name">{{ namequery }}</em>:</h3>
  {% if object_list %}
    {% for obj in object_list %}
      {{ obj.lname }} <br />
      {{ obj.clustering }} <br />
  {% endfor %}
  {% else %}
    <h3>No matches found.</h3>
  {% endif %}

views.py

class SearchView(generic.ListView):
model = Pitable 
template_name = 'chinook/search.html'


def get_queryset(self):
    try:
        namequery = self.kwargs['namequery']
    except:
        namequery = ''
    if (namequery != ''):
        object_list = self.model.objects.filter(lname = namequery)
    else:
        object_list = self.model.objects.all()
    return object_list

The return page display all data, shows the {{namequery}} is empty. Thanks!

1 Answer 1

2

There are quite a few things wrong here.

Firstly, 'namequery' is not a URL kwarg, it is a GET query parameter. You need to get it from self.request['namequery'].

Secondly, never ever use a blank except. The only exception that could possibly happen there is KeyError, so catch that. But a better way of writing all four lines would be:

namequery = self.request.GET.get('namequery')

Thirdly, to display the value of namequery in the template you need to add it to the context data.

def get_context_data(self, **kwargs):
    context = super(SearchView, self).get_context_data(**kwargs)
    context['namequery'] = self.request.GET.get('namequery')
    return context
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.