Django分页视图

时间:2013-12-08 16:38:41

标签: python django pagination

我在相同的视图中有搜索代码和分页代码,因此每当我查看分页的第二页时,我都会获得标准搜索页面... 在django教程中,每次调用视图时都会生成列表,在我的情况下,因为搜索表单总是与分页代码一起加载,在请求第二个分页时列表被删除... 我该怎么办?

这是简化的代码,因此您可以获得这个想法:

def main_page(request):
anuncios = []


#This is the search 
if request.method == 'POST':
    anuncios = Anuncio.objects.all().order_by('votos').reverse()[0:20]

# Pagination
paginator = Paginator(anuncios, 2)

page = request.GET.get('page')
try:
    p_anuncios = paginator.page(page)
except PageNotAnInteger:
    # If page is not an integer, deliver first page.
    p_anuncios = paginator.page(1)
except EmptyPage:
    # If page is out of range (e.g. 9999), deliver last page of results.
    p_anuncios = paginator.page(paginator.num_pages)

return render_to_response('main_page.html', RequestContext(request,
    {'form':form,
    'anuncios': p_anuncios,
    'vazio':vazio
    })
    )

由于

1 个答案:

答案 0 :(得分:0)

如果您的表单中包含一些影响分页器列表的字段,您可以执行类似这样的操作

<input type="hidden" name="current_page" value="{{ anuncios.number }}" />
<input type="submit" name="_next" value="next" />

在python中

page = request.GET.get('current_page','')
if page and page.isdigit() and '_next' in request.GET:
    try:
        p_anuncios = paginator.page(int(page) + 1)
    ...

然后你可以添加一个隐藏的输入字段名称=“page”与当前页面值和vor导航下一个和

相关问题