【发布时间】:2017-07-03 13:47:15
【问题描述】:
我正在尝试在 Django 中构建一个搜索表单,但不幸的是,我无法让代码按照教科书所说的那样工作(我正在使用 The Django Book)。我无法让表单提交,所以我添加了一个按钮,它解决了这个问题。不幸的是,现在我无法获得在视图中执行搜索功能的表单。它只是给了我一个 404 错误。
下面,请找到模板,
<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)
URLconf, 从 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.
【问题讨论】: