Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django Paginator在视图中_Python_Django_Pagination - Fatal编程技术网

Python Django Paginator在视图中

Python Django Paginator在视图中,python,django,pagination,Python,Django,Pagination,我在同一个视图中有搜索代码和分页代码,所以每当我试图查看分页的第二页时,我都会得到标准的搜索页。。。 在django教程中,每次调用视图时都会生成列表,在我的例子中,因为搜索表单总是与分页代码一起加载,所以在请求第二次分页时,列表会被删除。。。 我能做什么 以下是简化的代码,您可以了解: def main_page(request): anuncios = [] #This is the search if request.method == 'POST': anuncios =

我在同一个视图中有搜索代码和分页代码,所以每当我试图查看分页的第二页时,我都会得到标准的搜索页。。。 在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
    })
    )

谢谢

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

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

然后,您可以添加一个隐藏的输入字段name=“page”,其中包含当前页面值和vor导航a next和

anuncios=Anuncio.objects.all().order_by('votos')。reverse()[0:20]应该是anuncios=Anuncio.objects.all().order_by('-votos')[0:20]感谢提示KanuWhat如果我为分页创建一个不同的视图和模板,然后将其包含在搜索模板中?我使用'request.session=anuncios'解决了这个问题,我使用它存储搜索查询,这样就始终可以恢复查询,以便分页器正常工作。。。也在这里找到了帮助:无论如何,这不是一个优雅的解决方案,如果有人对这个问题有更好的想法,请告诉我。谢谢
page = request.GET.get('current_page','')
if page and page.isdigit() and '_next' in request.GET:
    try:
        p_anuncios = paginator.page(int(page) + 1)
    ...