我正在尝试在Django中构建一个搜索表单,但不幸的是我无法让代码工作,就像教科书所说的那样(我使用的是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 import include,url 来自django.contrib import admin 来自mysite2.views import hello,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 :(得分:0)
您的表单属性应使用直引号"
,而不是引号“
或”
。
<form action="/search/" method="get">
<input type = "text" name = "q">
您的错误消息search-form/“/search/“
表明您的代码确实包含“
,这不仅仅是Stack Overflow问题中的问题。