我是一名初学者并且进行了很多搜索,但每次我只得到“django to html”作为搜索结果。我正在学习本教程:
http://www.djangobook.com/en/2.0/chapter07.html
但在途中我无法将参数从html传递给view.py。
这是我的目录:
目录:mysite:
目录:书籍
目录:templates
search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form action="/search/" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
def search_form(request):
return render(request, 'books/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)
书籍urls.py
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^$',views.search_form,name='search_form'),
url(r'^$', views.search,name='search'),
]
和mysite目录中的urls.py
"""mysite URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Import the include() function: from django.conf.urls import url, include
3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import url,include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^books/', include('books.urls')),
]
现在问题是我输入的内容:http://127.0.0.1:8000/books/
它成功显示了表单的文本框和提交按钮,但是当我按提交时,它显示了我:
答案 0 :(得分:1)
首先,search_form
和search
结果需要两个不同的正则表达式。例如:
url(r'^$',views.search_form,name='search_form'),
url(r'^search/$', views.search,name='search'),
接下来,您需要更新表单的操作以指向搜索视图。由于您已将books/urls.py
包含/books/
前缀,因此您需要:
<form action="/books/search/" method="get">
最好使用url标记而不是硬编码您的网址。在这种情况下,你会这样做:
<form action="{% url 'search' %}" method="get">
答案 1 :(得分:1)
除了Alasdair的回答,我还会使用&#34; books:search&#34;清除命名空间:
<form action="{% url 'books:search' %}" method="get">
答案 2 :(得分:0)
网址/搜索/不存在,你没有定义它应该存在。
这将是/书籍/从您显示的URL文件判断。另外,请注意,不要使用http://www.djangobook.com/en/2.0/index.html
他们在主页面上发出警告,警告它不再是最新的。
使用masteringdjango.com和其他最新资源。