1
votes

I have a simple search app within a Django project which searches within a CMS admin. This is the form that generates the URL:

< form method="get" action="/search">
            < p>< label for="id_q">Search:
            < input type="text" name="q" id="id_q" />
            < input type="submit" value="Submit" />< /p>
        
, this is the URL:
(r'^search/$', 'search.views.search'), 
this is the view:
def search(request):
    query = request.GET['q']
    results = FlatPage.objects.filter(content__icontains=query)
    template = loader.get_template('search/search.html')
    context = Context({ 'query': query, 'results': results })
    response = template.render(context)
    return HttpResponse(response)
, this is the template:
< html>
    < head>
        < title>Search page
    < /head>
    < body>
        < p>You searched for "{{ query }}"; the results are listed below.< /p>
        < ul>
            {% for page in results %}
                < li>< a href="{{ page.get_absolute_url }}">{{ page.title }}< /a>< /li>
            {% endfor %}
        < /ul>
    < /body>
< /html>
but I keep receiving this error :
"Key 'q' not found in < QueryDict: {} >"
. Does anyone why and what can I do?
3

3 Answers

2
votes

Presumably this error is happening when you first request the page, before you submit a search term - so obviously, the q field is not found in the request. You just need to check for it first:

def search(request):
    if 'q' in request.GET:
        query = request.GET['q']
        results = FlatPage.objects.filter(content__icontains=query)
1
votes

You are using request.GET when you are posting the results in the submit. Use both the check mentioned by Daniel AND use POST instead:

def search(request):
    if 'q' in request.GET:
      query = request.GET['q']
      results = FlatPage.objects.filter(content__icontains=query)
    else:
      query = ""
      results = None
    template = loader.get_template('search/search.html')
    context = Context({ 'query': query, 'results': results })
    response = template.render(context)
    return HttpResponse(response)        
0
votes

You can change the line from query = request.GET['q'] to query = request.GET.get('q')

Note the get() function... Of course the other answers here also would work. See this similar question:

'instancemethod' object has no attribute '__getitem__'