我打算用Django写一个搜索应用程序
我在重定向到结果页时遇到NoReverseMatch
错误
我在这里发布了我的代码http://pastebin.com/AL4rG9NU
或者你可以在下面阅读
urls.py
urlpatterns = patterns('pylucene.views',
(r'^$', 'index'),
(r'^search/$', 'search'),
)
views.py
def index(request):
return render_to_response('pylucene/index.html', context_instance=RequestContext(request))
def search(request):
query = request.POST['query']
search_results = search_files(query)
return HttpResponseRedirect(reverse('pylucene.views.results', args=(search_results,)))
错误:
NoReverseMatch at /pylucene/search/ Reverse for 'pylucene.views.results' with arguments '([(u'Documents\\Dieu khien may tinh bang y nghi.txt', u'Dieu khien may tinh bang y nghi.txt'), '1 total matching documents.'],)' and keyword arguments '{}' not found.
def results(request, search_results):
return render_to_response('pylucene/results.html', {'search_results': search_results}, context_instance=RequestContext(request))
我读了几个类似的主题,但我无法解决我的问题。 请帮帮我 非常感谢你。
答案 0 :(得分:3)
我认为你并不是一成不变的reverse
功能如何运作,你在尝试什么是不可能的。
对于反向函数,您的url必须在urls.py上声明,例如:
#urls.py:
urlpatterns = patterns('blog.views',
(r'^$', 'index'),
url(r'^blog/(?P<slug>\d{4})/$', 'blog', name="blog-detail"),
)
现在,您可以在代码中执行
reverse('blog-detail', args=('django-urls',))
# the resolt of this is
# /blog/django-urls/
这就是逆向运作的方式。
我认为你不需要2个视图,但如果你真的想要:你必须这样做才能传递已执行的所有查询
def search(request):
query = request.POST['query']
search_results = search_files(query)
return results(request, search_results)
但我认为你能做的最好就是这个(使用GET):
def search(request):
query = request.GET['query'] # I think using get is better because you are GETing info
search_results = search_files(query) # better if returns a generator
return render_to_response('pylucene/results.html',
{'search_results': search_results},
context_instance=RequestContext(request)