【问题标题】:Django Paginator in view视图中的 Django 分页器
【发布时间】:2013-12-25 16:36:31
【问题描述】:

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

谢谢

【问题讨论】:

  • anuncios = Anuncio.objects.all().order_by('votos').reverse()[0:20] 应该是 anuncios = Anuncio.objects.all().order_by('-votos ')[0:20]
  • 感谢卡努的提示
  • 如果我为分页创建不同的视图和模板,然后将其包含在搜索模板中怎么办?

标签: python django pagination


【解决方案1】:

如果您的表单中的某些字段会影响分页器列表,您可以这样做

<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)
    ...

然后您可以添加一个隐藏的输入字段 name="page" 与当前页面值并导航到下一个和

【讨论】:

  • 我使用 'request.session = anuncios' 解决了这个问题,我用它来存储搜索查询,这样总是可以让分页器正常工作的查询。 Sessions ... 也在这里找到帮助:Paginating the results of a Django forms POST request
  • 无论如何,我觉得这不是一个优雅的解决方案,如果有人对这个问题有更好的想法,请告诉我。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-04
  • 2017-05-08
  • 1970-01-01
  • 2014-10-12
  • 2016-03-20
  • 1970-01-01
  • 2015-10-04
相关资源
最近更新 更多