Django学习笔记:组件-分页器

Django的分页器(paginator)

views.py:

from django.shortcuts import render
from app01.models import Book
from django.core.paginator import Paginator,EmptyPage

def index(request):
    """分页器的使用:"""
    book_list = Book.objects.all()
    paginator = Paginator(book_list, 10)
    
    try:
    	"""抛出异常"""
        current_page_num=request.GET.get("page",1)
        current_page=paginator.page(current_page_num)
        
    except EmptyPage as e:
        current_page_num = 1
        current_page = paginator.page(1)
    return render(request, "index.html",
                  {
     "current_page": current_page, "paginator": paginator, "current_page_num": int(current_page_num)})

index.html:


<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
head>
<body>

<ul>
    {% for book in current_page %}
        <li>{
    { book.title }} ---- {
    { book.price}}li>
    {% endfor %}

ul>

<nav aria-label="Page navigation">

  <ul class="pagination">

    {% if current_page.has_previous %}
        <li>
            <a href="?page={
      { current_page.previous_page_number }}" aria-label="Previous"><span aria-hidden="true">上一页span>a>
        li>
    {% else %}
        <li class="disabled"><a href="">上一页a>li>
    {% endif %}

    {% for num in paginator.page_range %}
        {% if num == current_page_num %}
            <li class="active"><a href="?page={
      { num }}">{
    { num }}a>li>
        {% else %}
            <li>
                <a href="?page={
      { num }}">{
    { num }}a>
            li>
        {% endif %}
      {% endfor %}

    {% if current_page.has_next %}
        <li>
            <a href="?page={
      { current_page.next_page_number }}" aria-label="Next"><span aria-hidden="true">下一页span>a>
        li>
    {% else %}
        <li class="disabled"><a href="">下一页a>li>
    {% endif %}

  ul>
nav>
body>
html>

你可能感兴趣的:(学习笔记,#Django,django,python)