2017-07-03 47 views
0

我想在Django中構建一個搜索表單,但不幸的是我無法讓代碼工作,因爲教科書說它會(我正在使用Django書)。我無法提交表單,因此我添加了一個修復該表單的按鈕。不幸的是,現在我無法獲得表單來執行視圖中的搜索功能。它只是給了我一個404錯誤。在Django構建一個搜索表單

下面,請找模板,

<html> 
    <head> 
    <title>Search</title> 
    </head> 
    <body> 
    <form action=「/search/「 method = 「get」> 
     <input type = 「text」 name = 「q」> 
     < button type = 「submit」> Submit</button> 
    </form> 
    </body> 
</html> 

請原諒缺乏支架。我無法弄清楚如何讓網站不把它解釋爲HTML。

認爲,

from django.shortcuts import render 
from django.http import HttpResponse 

# Create your views here. 
def search_form(request): 
    return render(request, "search_form.html") 
def search(request): 
    if 'q' in request.GET: 
     message = "You searched for: %r" % request.GET['q'] 
    else: 
     message = "You submitted an empty form." 
    return HttpResponse(message) 

URL配置, 從django.conf.urls導入已包括URL 從django.contrib中導入管理 從mysite2.views進口您好,current_datetime中,hours_ahead 從書本中導入意見

urlpatterns = [ 
    url(r'^admin/', include(admin.site.urls)), 
    url(r'^hello/$', hello), 
    url(r'^time/$', current_datetime), 
    url(r'^time/plus/(\d{1,2})/$', hours_ahead), 
    url(r'^search-form/$', views.search_form), 
    url(r'^search/$', views.search), 
] 

和錯誤頁面。

Page not found (404) 
Request Method: GET 
Request URL: http://127.0.0.1:8000/search-form/%E2%80%9C/search/%E2%80%9C?%E2%80%9Cq%E2%80%9D=A+Really+Good+Book 
Using the URLconf defined in mysite2.urls, Django tried these URL patterns, in this order: 
^admin/ 
^hello/$ 
^time/$ 
^time/plus/(\d{1,2})/$ 
^search-form/$ 
^search/$ 
The current path, search-form/「/search/「, didn't match any of these. 

回答

0

你的表單屬性應該使用直引號",不彎引號

<form action="/search/" method="get"> 
    <input type = "text" name = "q"> 

你的錯誤信息search-form/「/search/「意味着你的代碼確實包含,並且它不只是在你的堆棧溢出問題的問題。

+0

如何獲得直接報價? –

+0

這取決於你的文本編輯器,我不能幫你。 – Alasdair

+0

你的答案完美無缺!非常感謝! –