我只是不明白这里发生了什么,我花了很多时间尝试调试这个东西(我直接从Django书中读取)。我第一次加载网站时搜索功能实际上是DID工作。然后,我不得不做一些调试,以使其他部分工作,搜索功能突然崩溃。
当我提交表单时,我得到404告诉我“故事不存在”,尽管它实际上保存在我的管理员(因此我的数据库)中。附加到URL的Get查询似乎是正确的。它连接多个单词。
我知道这很简单,在我得不到之前它确实有效。同样有趣的是,我从这本代码中获取的书中没有包含管道(|)之后的第二个Q.我认为那是一个错字,每当我尝试删除它时,整个网站都会失败(包括管理员模板)。这也很奇怪。
from cms.models import Story, Category
from django.db.models import Q
from django.shortcuts import render_to_response, get_object_or_404
def search(request):
if 'q' in request.GET:
term = request.GET['q']
story_list = Story.objects.filter(
Q(title__contains=term) | Q(markdown_content__contains=term))
heading = "Search results"
return render_to_response("cms/story_list.html", locals())
答案 0 :(得分:2)
这是urlpattern的问题,当网址为http://localhost:8000/cms/search/?q=sec
时,它会匹配url模式url(r'^(?P<slug>[-\w]+)/$', 'object_detail', info_dict, name="cms-story")
,然后程序会找到名称为q
或其markdown_content
的故事1}}像q
,但现在你的数据库没有故事,因此它会告诉你“故事不存在”,现在你可以这样做:
from django.conf.urls.defaults import *
from cms.models import Story
info_dict = {'queryset':Story.objects.all(), 'template_object_name':'story'}
urlpatterns = patterns('cmsproject.cms.views',
url(r'^category/(?P<slug>[-\w]+)/$', 'category', name="cms-category"),
url(r'^search/$', 'search', name="cms-search"),
)
urlpatterns += patterns('django.views.generic.list_detail',
url(r'^(?P<slug>[-\w]+)/$', 'object_detail', info_dict, name="cms-story"),
url(r'^$', 'object_list', info_dict, name="cms-home"),
)
答案 1 :(得分:1)
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a search term.')
else:
storylist = Story.objects.filter(title__icontains=q)
return render_to_response('search_result.html',
{'packages': packages, 'query': q})
return render_to_response('cms/story_list.html', {'errors': errors})