Django 分页和“当前页面" [英] Django pagination and "current page"
问题描述
我目前正在开发一个 Django 应用程序,它将使用臭名昭著的分页"技术.我想弄清楚 django.core.paginator 模块是如何工作的.
I'm currently developing a Django application which will make use of the infamous "pagination" technique. I'm trying to figure out how the django.core.paginator module works.
我有一个带有问题模型的应用程序.我将使用这个分页器列出所有问题.每页将有 20 个问题.
I have an application with a Question model. I will be listing all of the questions using this paginator. There will be 20 questions per page.
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, ..." 我想以某种方式突出显示当前页面,就像许多网页做.
In the view, where I list the different pages as "... 2, 3, 4, 5, 6, ..." I want to highlight the current page somehow, like many pages do.
我真的想知道两件事:
- 如何让 Django 找出问题所在的页面?
- 如何编写模板以正确突出显示"当前访问的页面?
对不起,我忘记了这个问题的一部分.我还希望除当前页面之外的任何页面成为 /questions/{{ that_page.start_index }}
的链接.所以基本上每个页面链接都会链接到该页面上的第一个问题.
Sorry, I forgot part of this question. I would also like any page except for the current one to be a link to /questions/{{ that_page.start_index }}
. So basically every page link would link to the first question on that page.
推荐答案
嗯...我从你的评论中看到你不想做 ol' GET 参数,这就是 django.core.paginator 写的用于使用.为了做你想做的事,我想不出比预先计算每个问题所在的页面更好的方法.例如,您的视图最终将类似于:
Hmm... I see from your comment that you don't want to do the ol' GET parameter, which is what django.core.paginator was written for using. To do what you want, I can think of no better way than to precompute the page that each question is on. As an example, your view will end up being something like:
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 })
要突出显示模板中的当前页面,您可以执行类似的操作
To highlight the current page in the template, you'd do something like
{% 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_list 可以使用...
As for the items, you'll have two different object_lists to work with...
page.object_list
将是当前页面中的对象和
will be the objects in the current page and
page.paginator.object_list
将是所有对象,无论页面如何.这些项目中的每一个都有一个页面"变量,可以告诉您它们在哪个页面上.
will be all objects, regardless of page. Each of those items will have a "page" variable that will tell you which page they're on.
总之,您所做的事情听起来非常规.你可能想重新考虑,但无论如何,祝你好运.
That all said, what you're doing sounds unconventional. You may want to rethink, but either way, good luck.
这篇关于Django 分页和“当前页面"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!