开发实践5_project

要求:

(对作业要求的"Student"稍作了变换,表单名称为“Index”。)获得后台 Index 数据,作展示,要求使用分页器,包含上一页、下一页、当前页/总页。

结果:

开发实践5_project_第1张图片

① preparation (创建用户、app、注册、链接总路由等)

// 创建超级用户 terminal

python manage.py createsuperuser 

// 8000端口admin 

superuser login

( Create new app, install: )

terminal // 

python manage.py startapp page_app

setting //

install

total url //

path('page/', include('page_app.urls', namespace="page")),

② 编写Index table,编写用于展示的views、sub-urls等

models //

from django.db import models

class Index(models.Model):
    name = models.CharField(max_length=32, verbose_name="statistical index")
    category = models.CharField(max_length=32, verbose_name="application field")
    preference = models.FloatField(verbose_name="subjective recommendation degree")
    description = models.CharField(max_length=128, verbose_name="brief documentation", null=True)

    def __str__(self):
        return f"{self.name}_{self.category}"

    class Meta:
        verbose_name = "Index"
        verbose_name_plural = verbose_name + 'es'

    @classmethod
    def get_list(cls, **kwargs):
        filters = {}
        return cls.objects.filter(**filters)  # objects.all()

app admin  注册表单到admin主页,添加测试数据// //

from django.contrib import admin

from page_app.models import Index

models = [
    Index,
]

admin.site.register(models)

views //

from django.shortcuts import render
from django.core.paginator import Paginator, InvalidPage

from djangoProject.settings import PAGE_SIZE
from page_app.models import Index


def list_index(request):
    page_num = request.GET.get("page_num", default=1)  # 页码 可以通过/?page=k传参,路由与视图函数不必维护param
    indexes = Index.get_list()  # 
    paginator = Paginator(indexes, PAGE_SIZE)
    try:
        data = paginator.page(page_num)
    except InvalidPage:
        data = paginator.page(1)
    return render(request, "staticindex.html", {"data": data, "paginator": paginator})
    # 记得不要locals().减少缓存中的数据量。

setting //

# 设置分页大小
PAGE_SIZE = 3

templates //

开发实践5_project_第2张图片

你可能感兴趣的:(数据库)