我陷入了一个困境,我应该能够在页面上输入搜索查询,并且 django 应该返回匹配页面的列表(如果有)。但它没有向我显示任何页面,即使它在那里,并且给了我一个错误。假设我有一个页面,其内容为一,当我搜索时,我收到此错误:
Page not found (404)
Request Method:GET
Request URL:http://xxx.x.x.x:8000/search/csrfmiddlewaretoken=W6n1O1vQCMyDojxEkR4mPnRrVz9lYVt1&q=one
No FlatPage matches the given query.
请指出我哪里做错了。谢谢。
我的观点.py:
from django.http import HttpResponse
from django.template import loader, Context
from django.contrib.flatpages.models import FlatPage
def search(request):
query = request.GET['q']
resuts = FlatPage.objects.filter(content__icontains=query)
template = loader.get_template('search/search.html')
context = Context({
'query':query,
'resuts':resuts
})
response = template.render(context)
return HttpResponse(response)
url.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': 'C:/Users/Kakar/web/cms/static/js/tinymce/' }),
(r'', include('django.contrib.flatpages.urls')),
(r'^search/$', 'search.views.search'),
)
设置.py:
In the installed-apps, I have installed 'search'.
默认.html:
<html>
<head>
<title>{{ flatpage.title }}</title>
</head>
<body>
<form method="get" action="/search/">
{% csrf_token %}
<p><label for="id_q">Search:</label>
<input type="text" name="q" id="id_q" />
<input type="submit" value="Submit" /></p>
</form>
<h1>{{ flatpage.title }}</h1>
{{ flatpage.content }}
</body>
</html>
搜索.html:
<html>
<head>
<title>Search</title>
</head>
<body>
<p>You searched for "{{query}}"; the results are listed below.</p>
{% if results %}
<ul>
{% for page in results %}
<li>
<a href="{{page.get_absolute_url}}">{{page.title}}</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No results.</p>
{% endif %}
</body>
</html>
最佳答案
尝试更改 URL 匹配的顺序。
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/(?P<path>.*)$', 'django.views.static.serve', { 'document_root': 'C:/Users/Kakar/web/cms/static/js/tinymce/' }),
(r'^search/$', 'search.views.search'),
(r'', include('django.contrib.flatpages.urls')),
)
就像 the documentation 中一样
此外,由于某种原因,您在查询参数中缺少 ?
。
还有一个问题:您有一个拼写错误。您正在上下文中发送 resuts
,并在 HTML 中执行 {{results}}
关于django搜索页面未找到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17952255/