2

我被困在我应该能够在页面上输入搜索查询的地方,如果有的话,django 应该返回匹配页面的列表。但它没有显示任何页面,即使它在那里,并且给了我一个错误。假设我有一个内容为一的页面,当我搜索时,我收到此错误:

找不到页面 (404)

请求方法:GET

请求网址: http: //xxx.xxx :8000/search/csrfmiddlewaretoken=W6n1O1vQCMyDojxEkR4mPnRrVz9lYVt1&q=one

没有 FlatPage 匹配给定的查询。

请指出我在哪里做错了。谢谢你。

我的意见.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)

网址.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:

在已安装的应用程序中,我安装了“搜索”。

默认.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>
4

1 回答 1

2

尝试更改 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')),
)

就像在文档中一样

此外,由于某种原因,您缺少?查询参数中的 。

还有一个问题:你有一个错字。您resuts在上下文中发送,并{{results}}在 HTML 中执行

于 2013-07-30T16:23:41.667 回答