我目前正在开发一个 Django 应用程序,它将利用臭名昭著的“分页”技术。我试图弄清楚 django.core.paginator 模块是如何工作的。
我有一个带有问题模型的应用程序。我将使用此分页器列出所有问题。每页有 20 个问题。
def show_question(question_pk):
questions = Question.objects.all()
paginator = Paginator(questions, 20)
page = ... # Somehow figure out which page the question is on
return render_to_response('show_question.html', { 'page' : page })
在视图中,我将不同的页面列为“... 2, 3,4, 5, 6, ...”我想以某种方式突出显示当前页面,就像许多页面一样。
我确实想知道两件事:
- 如何让 Django 找出问题所在的页面?
- 我将如何编写模板以正确“突出显示”当前访问的页面?
编辑:抱歉,我忘记了这个问题的一部分。我还希望除当前页面之外的任何页面都可以链接到/questions/{{ that_page.start_index }}
。因此基本上每个页面链接都会链接到该页面上的第一个问题。
嗯...我从你的评论中看到你不想执行 ol' GET 参数,这是 django.core.paginator 编写的用途。为了做你想做的事,我想不出比预先计算每个问题所在的页面更好的方法了。例如,您的视图最终将类似于:
ITEMS_PER_PAGE = 20
def show_question(question_pk):
questions = Question.objects.all()
for index, question in enumerate(questions):
question.page = ((index - 1) / ITEMS_PER_PAGE) + 1
paginator = Paginator(questions, ITEMS_PER_PAGE)
page = paginator.page(questions.get(pk=question_pk).page)
return render_to_response('show_question.html', { 'page' : page })
要突出显示模板中的当前页面,您可以执行类似的操作
{% for i in page.paginator.page_range %}
{% ifequal i page.number %}
<!-- Do something special for this page -->
{% else %}
<!-- All the other pages -->
{% endifequal %}
{% endfor %}
至于项目,您将有两个不同的 object_lists 可以使用......
page.object_list
将是当前页面中的对象并且
page.paginator.object_list
将是所有对象,无论页面如何。这些项目中的每一个都会有一个“页面”变量,它会告诉您它们位于哪个页面。
总而言之,你所做的事情听起来很不传统。您可能需要重新考虑,但无论如何,祝您好运。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)