2013-02-25 47 views
1

我不知道爲什麼這發生在我的兩個搜索功能之間。Djangobooks搜索欄錯誤第7章

這裏是我的第一檢索功能

def search(request): 
    if 'q' in request.GET and request.GET['q']: 
    q = request.GET['q'] 
    books = Book.objects.filter(title__icontains = q) 
    return render_to_response('search_results.html', {'books': books, 'query': q}) 
    else: 
    return render_to_response('search_form.html', {'error': True}) 

有了這個功能,當我進入

http://127.0.0.1:8000/search/ 

到我的瀏覽器,你會顯示一個搜索欄和我創建了一個消息。此外,當我按下搜索按鈕,鏈接會自動如果我進入

http://127.0.0.1:8000/search/ 

到更新到

http://127.0.0.1:8000/search/?q= 

但是對於我的搜索功能

def search(request): 
     error = False 
     if 'q' in request.GET['q']: 
      q = request.GET['q'] 
      if not q: 
      error = True 
      else: 
      books = Book.objects.filter(title__icontains = q) 
      return render_to_response('search_results.html', {'books': books, 'query': q}) 
    return render_to_response('search_form.html',{'error':error}) 

的第二版我會得到

Exception Type:  MultiValueDictKeyError 
    Exception Value: "Key 'q' not found in <QueryDict: {}>" 

如果我是手動進行的瀏覽器

http://127.0.0.1:8000/search/?q= 

錯誤消息就會消失的鏈接,但如果我表現的搜索,所有我得到的是一個搜索欄,什麼也不做,除了更新鏈接到任何我輸入到搜索欄並運行搜索。

EX: searched for eggs --> http://127.0.0.1:8000/search/?q=eggs 

這裏是我的HTML文件

search_results.html

<p>You searched for: <strong>{{ query }}</strong></p> 

    {% if books %} 
     <p>Found {{ books|length }} book{{ books|pluralize }}.</p> 
     <ul> 
      {% for book in books %} 
      <li>{{ book.title }}</li> 
      {% endfor %} 
     </ul> 
    {% else %} 
     <p>No books matched your search criteria.</p> 
    {% endif %} 

search_form.html

<html> 
    <head> 
     <title>Search</title> 
    </head> 
    <body> 
     {% if error %} 
      <p style = "color: red;">Please submit a search term.</P> 
     {% endif %} 
     <form action = "/search/" method = "get"> 
      <input type = "text" name = "q"> 
      <input type = "submit" value = "Search"> 
     </form> 
    </body> 
    </html> 

任何幫助,非常感謝!謝謝!

回答

4

您鍵入:

if 'q' in request.GET['q']: 

,您應鍵入:

if 'q' in request.GET: 

這是因爲您嘗試訪問到缺少項目失敗。
你也可以這樣做:

if request.GET.get('q', False): 
+0

... OMG如何我沒有看到這一點....非常感謝! – Liondancer 2013-02-25 12:00:43

1

要添加到什麼祖魯說,你可以使用get()方法屬於字典收拾碼一點點:

def search(request): 

    query = request.GET.get("q", None) 

    if query: 
     books = Book.objects.filter(title__icontains = query) 
     return render_to_response("search_results.html", {"books": books, "query": query}) 

    # if we're here, it's because `query` is None 
    return render_to_response("search_form.html", {"error": True}) 
+0

這看起來更清潔!謝謝您的意見!! – Liondancer 2013-02-25 12:15:21