文章目录
-
- 1. 函数视图使用分页
- 2. 类视图使用分页
- 3. 展示分页的通用模板
- Django自带 Paginator 类来实现分页功能
1. 函数视图使用分页
- page_obj: 分页后的对象列表,在模板中使用for循环遍历即可
- is_paginated: 可选参数。当总页数不超过1页,值为False,此时模板不显示任何分页链接
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import Article
from django.shortcuts import render
def article_list(request):
queryset = Article.objects.filter(status='p').order_by('-pub_date')
paginator = Paginator(queryset, 10)
page = request.GET.get('page')
try:
page_obj = paginator.page(page)
except PageNotAnInteger:
page_obj = paginator.page(1)
except EmptyPage:
page_obj = paginator.page(paginator.num_pages)
is_paginated = True if paginator.num_pages > 1 else False
context = {
'page_obj': page_obj, 'is_paginated': is_paginated}
return render(request, 'blog/article_list.html', context)
2. 类视图使用分页
- 基于类的视图ListView中使用分页,只需设置paginate_by这个参数即可
- 它同样会向模板传递 page_obj 和 is_paginated 这2个参数
from django.views.generic import ListView
from .models import Article
class ArticleListView(ListView):
queryset = Article.objects.filter(status='p').order_by('-pub_date')
template_name = "blog/article_list.html"
paginate_by = 10
3. 展示分页的通用模板
<ul>
{
% for article in page_obj %}
<li>{
{
article.title }}</li>
{
% endfor %}
</ul>
{
% if is_paginated %}
<div class="pagination">
<span class="step-links">
{
% if page_obj.has_previous %}
<a href="?page=1">« first</a>
<a href="?page={
{ page_obj.previous_page_number }}">上一页</a>
{
% endif %}
<span class="current">
Page {
{
page_obj.number }} of {
{
page_obj.paginator.num_pages }}.
</span>
{
% if page_obj.has_next %}
<a href="?page={
{ page_obj.next_page_number }}">下一页</a>
<a href="?page={
{ page_obj.paginator.num_pages }}">last »</a>
{
% endif %}
</span>
</div>
{
% endif %}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
{
% if page_obj %}
<ul>
{
% for article in page_obj %}
<li> {
{
article.title }</li>
{
% endfor %}
</ul>
{
{
% if is_paginated %}
<ul class="pagination">
{
% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?page={
{ page_obj.previous_page_number }}">Previous</a></li>
{
% else %}
<li class="page-item disabled"><span class="page-link">Previous</span></li>
{
% endif %}
{
% for i in page_obj.paginator.page_range %}
{
% if page_obj.number == i %}
<li class="page-item active"><span class="page-link"> {
{
i }} <span class="sr-only">(current)</span></span></li>
{
% else %}
<li class="page-item"><a class="page-link" href="?page={
{ i }}">{
{
i }}</a></li>
{
% endif %}
{
% endfor %}
{
% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?page={
{ page_obj.next_page_number }}">Next</a></li>
{
% else %}
<li class="page-item disabled"><span class="page-link">Next</span></li>
{
% endif %}
</ul>
{
% endif %}
{
% else %}
{
{
% endif %}