2017-07-03 119 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

你的答案完美无缺!非常感谢! –