如何在第二个结果页面上保留搜索词

时间:2012-04-27 09:53:32

标签: jquery python django search pagination

我正在使用Django开发一个应用程序,我在一个非常大的数据库和一个Paginator中进行了一个简单的搜索。问题是当我尝试转到第二个结果页面时,我会从链接中丢失搜索到的术语。

我试图用JQuery重写输入字段中的搜索词,但是没有用。我试图将值从服务器端重新发送到输入字段,也不起作用。

如何设置保留第二页结果?还有其他提示吗?

这是我的代码,至少是相关部分:

results.html:

...
<form method="POST" id="searchForm"  action="{% url ps.views.search page=1 searchTerm='__search_term__' %}">
    {% csrf_token %}
    <input type="text" id="billSearched">
    <input type="submit" value="{% trans "Look for" %}">
</form>
 ...
<div class="pagination">
    {% if current_page.has_previous %}
        <a href="{% url ps.views.search page=current_page.previous_page_number searchTerm='__search_term__' %}">previous</a>
    {% endif %}

    <span class="current">
        Page {{ current_page.number }} of {{ current_page.paginator.num_pages }}
    </span>

    {% if current_page.has_next %}
        <a href="{% url ps.views.search page=current_page.next_page_number searchTerm='__search_term__' %}">next</a>
    {% endif %}
</div>

search.py​​:

def search(request,page,searchTerm):
    found_bills = Bill.objects.filter(name__icontains=searchTerm)
    searchedWord = str(searchTerm)
    paginator = Paginator(found_bills,25)
    try:
        current_page = paginator.page(page)
    except (EmptyPage, InvalidPage):
        current_page = paginator.page(paginator.num_pages)
    bills_list = list(current_page.object_list)
    return render_to_response('results.html',{"bills_list":bills_list,"current_page":current_page,"searchTerm":searchTerm,"searchedWord":searchedWord},context_instance=RequestContext(request))

而且 urls.py 虽然我不确定它是否有用:)

urlpatterns = patterns('',
    url(r'^$','ps.views.bills',name="bills"),
    url(r'^i18n/', include('django.conf.urls.i18n')),
    url(r'^search/(?P<page>\d+)/(?P<searchTerm>\w*)','ps.views.search',name="search"),)


I should mention that in the address bar the searched term when I go to page 2 is "__search_term__".

即。 http://127.0.0.1:8000/search/2/__search_term__

提前谢谢! :)

1 个答案:

答案 0 :(得分:2)

将您的表单方法更改为GET而不是POST,然后使用搜索字词构建链接作为URL的查询字符串的一部分,如下所示...

<a href="?page={{ contacts.previous_page_number }}">previous</a>

https://docs.djangoproject.com/en/dev/topics/pagination/