1

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

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

我怎样才能设法将它保留在结果的第二页?还有其他提示吗?

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

结果.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>

搜索.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__".

IEhttp://127.0.0.1:8000/search/2/__search_term__

先感谢您!:)

4

1 回答 1

2

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

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

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

于 2012-04-27T10:02:29.323 回答