django搜索页面未找到错误

时间:2013-07-30 16:17:25

标签: django django-templates django-views

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

  

找不到页面(404)

     

请求方法:GET

     

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

     

没有FlatPage匹配给定的查询。

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

my views.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)

urls.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'),
)

settings.py:

  

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

default.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>

search.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>

1 个答案:

答案 0 :(得分:1)

尝试更改网址匹配的顺序。

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}}