Django 前端BootCSS 實現分頁

lyshark發表於2021-11-02

通過使用bootstrap框架,並配合Django自帶的Paginator分頁元件即可實現簡單的分頁效果。

1.建立MyWeb專案

python manage.py startapp MyWeb

2.修改settings.py配置檔案,匯入我們的app的名字,去掉csrf這個選項

# 遮蔽一項
MIDDLEWARE = [
    #'django.middleware.csrf.CsrfViewMiddleware'
]

# 新增一項
TEMPLATES = [
	'MyWeb.apps.MywebConfig'
]

3.來urls.py裡面寫一條路由,名字就叫index/對映到views.index函式下處理此請求

from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index)
]

4.最後在myweb裡面的views.py設定一個檢視函式,最後執行

from django.shortcuts import render
from django.shortcuts import HttpResponse
from MyWeb import models

def index(requests):
    return HttpResponse("abcd")

5.配置資料庫檔案models.py並設定以下內容

from django.db import models

# 建立使用者表
class User(models.Model):
    id = models.AutoField(primary_key=True)
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

6.更新資料庫與資料表

python manage.py makemigrations   # 將你的資料庫變動記錄下來(並不會幫你建立表)
python manage.py migrate          # 將你的資料庫變動正在同步到資料庫中

7.增加一個新的view並使用rand()函式.

首先在urls.py中增加路由

from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),
    path('rand/',views.rand)
]

其次在view.py檢視中增加生成函式.

from django.shortcuts import render
from django.shortcuts import HttpResponse
from MyWeb import models
import random

# 首頁
def index(requests):
    return HttpResponse("abcd")

# 生成測試資料
def rand(request):
    for i in range(1,1000):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")

啟動django並訪問http://127.0.0.1:8000/rand/等待資料生成結束.

8.在templates模板中,新增一個page.html頁面。

<!--name: page.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.lyshark.com/bootstrap/4.5.0/css/bootstrap.min.css">
</head>
<body>
<table class="table table-sm table-hover">
    <thead>
        <tr class="table-success">
            <th> 序號</th> <th> 使用者名稱</th> <th> 使用者密碼</th>
        </tr>
    </thead>
    <tbody>
        {% for article in user_list %}
            <tr class="table-primary">
                <td>{{ article.id }}</td>
                <td>{{ article.username }}</td>
                <td>{{ article.password }}</td>
            </tr>
        {% endfor %}
    </tbody>
</table>
<nav class="d-flex justify-content-center" aria-label="Page navigation example">
    <ul class="pagination">
        <li class="page-item"><a class="page-link" href="./page?id=1">首頁</a></li>
        {% if user_list.has_previous %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.previous_page_number }}">上一頁</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#">上一頁</a></li>
        {% endif %}

        {% for item in page_range %}
            {% if item == currentPage %}
                <li class="page-item active"><a class="page-link" href="./page?id={{ item }}">{{ item }}</a></li>
            {% else %}
                <li class="page-item"><a class="page-link" href="./page?id={{ item }}">{{ item }}</a></li>
            {% endif %}
        {% endfor %}

        {% if user_list.has_next %}
            <li class="page-item"><a class="page-link" href="./page?id={{ user_list.next_page_number }}">下一頁</a></li>
        {% else %}
            <li class="page-item disabled"><a class="page-link" href="#">下一頁</a></li>
        {% endif %}
        <li class="page-item"><a class="page-link" href="./page?id={{ paginator.num_pages }}">尾頁</a></li>
    </ul>
</nav>

<div style="text-align: center;" class="alert alert-dark">
   統計: {{ currentPage }}/{{ paginator.num_pages }} 共查詢到:{{ paginator.count }} 條資料 頁碼列表:{{ paginator.page_range }}
</div>
</body>
</html>

9.最後在路由曾以及view中增加對應的URL以及路由函式.

首先在urls.py中增加一條新路由.

from django.contrib import admin
from django.urls import path
from MyWeb import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/',views.index),
    path('rand/',views.rand),
    path('page',views.page)
]

接著在views.py中增加一個page函式.

from django.shortcuts import render
from django.shortcuts import HttpResponse
from MyWeb import models
import random

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

# 首頁
def index(requests):
    return HttpResponse("abcd")

# 生成測試資料
def rand(request):
    for i in range(1,1000):
        chars = []
        pasd = []
        for x in range(1,8):
            chars.append(random.choice('abcdefghijklmnopqrstuvwxyz'))
            pasd.append(random.choice('0987654321'))
        user = "".join(chars)
        pwd = "".join(pasd)
        models.User.objects.create(username=user, password=pwd)
    return HttpResponse("ok")

# 分頁函式
def page(request):
    user = models.User.objects.all()
    paginator = Paginator(user, 10)
    currentPage = int(request.GET.get("id",1))

    if paginator.num_pages > 15:
        if currentPage-5 < 1:
            pageRange = range(1,11)
        elif currentPage+5 > paginator.num_pages:
            pageRange = range(currentPage-5,paginator.num_pages)
        else:
            pageRange = range(currentPage-5,currentPage+5)
    else:
        pageRange = paginator.page_range

    try:
        user_list = paginator.page(currentPage)
    except PageNotAnInteger:
        user_list = paginator.page(1)
    except:
        user_list = paginator.page(paginator.num_pages)

    return render(request,"page.html",{"user_list":user_list,
                                       "paginator":paginator,
                                       "page_range":pageRange,
                                       "currentPage":currentPage})

準備就緒之後,直接訪問http://127.0.0.1:8000/page即可看到分頁顯示效果.

相關文章