Reputation: 16690
I just don't understand what's going on here and I've spent a lot of time attempting to debug this thing (which I took directly from a Django book). The search funcationality actually DID work the first time I loaded the site. I then had to do some debugging to make other pieces work and the search functionality suddenly broke.
When I submit the form, I get 404 telling me that the "story does not exist" although it is in fact in saved in my admin (and therefore my database). The Get query appended to the URL seems right. It concatenates multiple words.
I know that this is so simple and it actually worked before I don't get it. Also interesting, the book that I took this code from didn't include a second Q after the pipe (|). I thought that was a typo and whenever I try to remove it, the whole site fails (including the admin template). That's also strange.
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())
Upvotes: 0
Views: 742
Reputation: 21
That is the problem of urlpattern, when the url is http://localhost:8000/cms/search/?q=sec
, it will match the urlpattern url(r'^(?P<slug>[-\w]+)/$', 'object_detail', info_dict, name="cms-story")
, then the program will find the story whose name like q
or whose markdown_content
like q
, but now your database has not the story, therefore it will tell you "story does not exist", now you can do it like this:
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"),
)
Upvotes: 2
Reputation: 80
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})
Upvotes: 1