将Django表单的结果分页

2024-05-16 13:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Django表单通过POST进行过滤/分面搜索,我想使用Django的paginator类来组织结果。在不同页面之间传递客户端时,如何保留原始请求?换句话说,当我将另一个页面的GET请求传递回视图时,似乎会丢失POST数据。我已经看到一些使用AJAX只刷新页面结果块的建议,但我想知道是否有Django本机机制来实现这一点。

谢谢。


Tags: 数据django视图客户端表单getajax页面
3条回答

如果要在以后的请求中访问存储数据,则必须将其存储在某处。Django提供了几种存档方法:

1)您可以使用sessions来存储查询:访问您站点的每个访问者都将获得一个空会话对象,并且您可以在该对象中存储您想要的任何内容,这类似于dict。缺点:一个访问者不能同时执行多个分页搜索。

2)使用cookie:如果设置了存储在客户端的cookie,浏览器会将cookie的数据附加到每个可以访问它的请求中。Cookie对服务器更友好,因为您不需要服务器上的会话管理器,但是存储在Cookie中的数据对客户端可见(并且可编辑)。缺点:和以前一样。

3)使用隐藏字段:您可以在搜索结果页上添加包含一些隐藏字段的表单,并将查询存储在其中。然后,客户机将在您提交表单时重新发送查询。缺点:您必须使用带有提交按钮的表单对页面进行分页(简单的链接不起作用)。

4)创建包含查询的链接:您也可以使用GET而不是POST。例如,可以有一个类似"/search/hello+world/?order=votes"的链接和一个类似"/search/hello+world/2/?order-votes"的“分页链接”。然后可以很容易地从URL检索查询。缺点:通过GET可以发送的最大数据量是有限的(但对于简单的搜索来说,这不应该是个问题)。

5)使用组合:您可能希望将所有数据存储在会话或数据库中,并通过生成的密钥访问它们,该密钥可以放在URL中。然后,url可能看起来像“/search/029af239ccd23/2"(第2页),您可以使用该键访问以前存储的大量数据。这消除了溶液1和溶液4的缺点。新缺点:工作量大:)

6)使用AJAX:使用AJAX,可以将数据存储在客户端的一些js变量中,然后将这些变量传递给其他请求。因为ajax只会更新结果列表,所以变量不会丢失。

从tux21b中读到了非常好的答案,我决定实现第一个选项,即使用会话存储查询。这是一个搜索房地产数据库的应用程序。下面是视图代码(使用django 1.5):

def main_search(request):
    search_form = UserSearchForm()
    return render(request, 'search/busca_inicial.html', {'search_form': search_form})


def result(request):
    if request.method == 'POST':
        search_form = UserSearchForm(request.POST)
        if search_form.is_valid():
            # Loads the values entered by the user on the form. The first and the second
            # are MultiChoiceFields. The third and fourth are Integer fields
            location_query_list = search_form.cleaned_data['location']
            realty_type_query_list = search_form.cleaned_data['realty_type']
            price_min = search_form.cleaned_data['price_min']
            price_max = search_form.cleaned_data['price_max']
            # Those ifs here populate the fields with convenient values if the user
            # left them blank. Basically the idea is to populate them with values
            # that correspond to the broadest search possible.
            if location_query_list == []:
                location_query_list = [l for l in range(483)]
            if realty_type_query_list == []:
                realty_type_query_list = [r for r in range(20)]
            if price_min == None:
                price_min = 0
            if price_max == None:
                price_max = 100000000
            # Saving the search parameters on the session
            request.session['location_query_list'] = location_query_list
            request.session['price_min'] = price_min
            request.session['price_max'] = price_max
            request.session['realty_type_query_lyst'] = realty_type_query_list
    # making a query outside the if method == POST. This logic makes the pagination     possible.
    # If the user has made a new search, the session values would be updated. If not,
    # the session values will be from the former search. Of course, that is what we want  because
    # we want the 'next' and 'previous' pages correspond to the original search
    realty_list_result =    FctRealtyOffer.objects.filter(location__in=request.session['location_query_list']
                                                    ).filter(price__range=(request.session['price_min'], request.session['price_max'])
                                                   ).filter(realty_type__in=request.session['realty_type_query_lyst'])
    # Here we pass the list to a table created using django-tables2 that handles sorting
    # and pagination for us
    table = FctRealtyOfferTable(realty_list_result)
    # django-tables2 pagination configuration
    RequestConfig(request, paginate={'per_page': 10}).configure(table)

    return render(request, 'search/search_result.html', {'realty_list_size': len(realty_list_result),
                                                      'table': table})

希望有帮助!如果有人有任何改进建议,欢迎。

作为@rvnovaes,一种使用session解决问题的方法。

他的解决方案的缺点是,如果有许多搜索字段,则必须编写许多行代码,并且如果在结果页中显示搜索表单,则所有字段都将为空,而它们应保留其值。

因此,我宁愿将所有post数据保存在session中,如果定义了会话,则在视图的开头强制使用request.post和request.method的值:

""" ... """
if not request.method == 'POST':
    if 'search-persons-post' in request.session:
        request.POST = request.session['search-persons-post']
        request.method = 'POST'

if request.method == 'POST':
    form = PersonForm(request.POST)
    request.session['search-persons-post'] = request.POST
    if form.is_valid():
        id = form.cleaned_data['id']
""" ... """

更多信息here

相关问题 更多 >