5-Django项目--分页与搜索(资产页面)

目录

views/asset_data.py

asset_data/asset_data.html

搜索与分页笔记:

搜索

整数搜索

字符串搜索

分页


views/asset_data.py

# -*- coding:utf-8 -*-
from django.shortcuts import render, redirect, HttpResponse
from django.utils.safestring import mark_safe
from demo_one import models
from django import forms
import random
# 正则校验
from django.core.validators import RegexValidator
# 异常类
from django.core.exceptions import ValidationError


# 资产信息展示
def asset_data(request):
    # 直接写入列表数据
    data_time = ["2024-5-14", "2024-5-13", "2024-5-12", "2024-5-11", "2024-5-10", "2024-5-18"]
    name_list = ["一灯大师", "马青雄", "马钰", "小沙弥", "木华黎", "丘处机", "沈青刚",
                 "书生", "天竺僧人", "王处一", "王罕", "尹志平", "包惜弱", "冯衡",
                 "孙不二", "札木合", "华筝", "李萍", "刘玄处", "刘瑛姑", "吕文德",
                 "乔寨主", "曲三", "曲傻姑", "全金发", "汤祖德", "朱聪", "陈玄风",
                 "灵智上人", "陆乘风", "陆冠英", "沙通天", "完颜洪烈", "完颜洪熙", "吴青烈",
                 "杨铁心", "余兆兴", "张阿生", "张十五", "忽都虎", "欧阳峰", "欧阳克",
                 "者勒米", "周伯通", "段天德", "郭靖", "郭啸天", "郝大通", "洪七公",
                 "姜文", "柯镇恶", "枯木", "南希仁", "胖妇人", "胖丐", "胖子",
                 "都史", "钱青健", "桑昆", "铁木真", "盖运聪", "黄蓉", "黄药师",
                 "梁子翁", "梅超风", "渔人", "博尔忽", "博尔术", "程瑶迦", "韩宝驹",
                 "焦木和尚", "鲁有脚", "穆念慈", "彭长老", "彭连虎", "童子", "窝阔台",
                 "简管家", "裘千仞", "裘千丈", "瘦丐", "察合台", "酸儒文人", "谭处端", ]
    for name in name_list:
        number = str(name_list.index(name) + 1)
        if len(number) <= 1:
            number = "2024" + "00" + number
            # models.Asset.objects.create(name=name, mobile=f"153{random.randint(11111111, 99999999)}",
            #                             data_time=random.choice(data_time), data_id=number)
        elif len(number) <= 2:
            number = "2024" + "0" + number
            # models.Asset.objects.create(name=name, mobile=f"153{random.randint(11111111, 99999999)}",
            #                             data_time=random.choice(data_time), data_id=number)
        else:
            number = "2024" + number
            # models.Asset.objects.create(name=name, mobile=f"153{random.randint(11111111, 99999999)}",
            #                             data_time=random.choice(data_time), data_id=number)
    # data_list = models.Asset.objects.filter(data_id__contains="00")

    # 搜索
    dict_data = {}
    # 获取搜索框当中的内容
    value = request.GET.get("search")
    # 如果value有值,则进行搜索,没有值,全部展示
    if value:
        # 字典的键是查询条件,值是查询的内容
        dict_data["data_id__contains"] = value

    # print(data_list)

    # 分页
    page = int(request.GET.get("page", 1))  # 当前所在的页面
    page_size = 10  # 每页展示十条信息

    # 寻找切片的开始和结束
    start = (page-1) * page_size
    end = page * page_size

    # 字典当中如果有条件,则根据条件进行查询,如果是空,则查询全部,最终返回列表格式
    data_list = models.Asset.objects.filter(**dict_data)[start:end]
    # 查询总共有多少条数据
    data_asset_count = models.Asset.objects.filter(**dict_data).count()
    # 总数除以10,如果有余数,则单独添加一页
    page_count, div = divmod(data_asset_count, page_size)
    if div:
        page_count += 1

    # 见算出当前页的前两页和后两页
    plus = 2
    # 如果当前数据表的总页码小于 5页
    if page_count <= 2*plus + 1:
        start_page = 1
        end_page = page_count
    else:
        # 当前选中的页数小于等于三
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            # 当前页 + 2
            if(page + plus) > page_count:
                start_page = page_count - plus * 2
                end_page = page_count
            else:
                start_page = page - plus
                end_page = page + plus


    # 存放分页的li标签
    page_str_list = []
    # 首页
    page_str_list.append(
        f'<li><a href="?page=1" aria-label="Previous"><span aria-hidden="true">首页</span></a></li>')

    # 上一页
    if page > 1:
        page_str_list.append(f'<li><a href="?page={page -1}" aria-label="Previous"><span aria-hidden="true">«</span></a></li>')
    else:
        page_str_list.append(
            f'<li class="disabled"><a href="#" aria-label="Previous"><span aria-hidden="true">«</span></a></li>')

    for page_num in range(start_page, end_page+1):
        if page_num == page:
            page_ele = f'<li class="active"><a href="?page={page_num}">{page_num}</a></li>'
        else:
            page_ele = f'<li><a href="?page={page_num}">{page_num}</a></li>'
        page_str_list.append(page_ele)


    # 下一页
    if page < page_count:
        page_str_list.append(f'<li><a href="?page={page+1}" aria-label="Next"><span aria-hidden="true">»</span></a></li>')
    else:
        page_str_list.append(
            f'<li class="disabled"><a href="#" aria-label="Next"><span aria-hidden="true">»</span></a></li>')

    # 尾页
    page_str_list.append(
        f'<li><a href="?page={page_count}" aria-label="Previous"><span aria-hidden="true">尾页</span></a></li>')
    # 将列表当中的字符串传递给html,并且一标签的形式展示
    page_string = mark_safe("".join(page_str_list))
    return render(request, "asset_data/asset_data.html", {
        "data_list": data_list,
        "page_string": page_string
    })


# 添加资产
class Addasset(forms.ModelForm):
    # 创建一个手机号输入框,校验手机号的格式
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r"^1[3-9]\d{9}$", "请输入正确格式的手机号")]
    )

    class Meta:
        model = models.Asset
        fields = ["name", "mobile", "data_time", "data_id", "ret_data"]
        # 排除某些字段
        # exclude = ["name"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "autocomplete": "off"}

    # 数据库做重复值判断 clean_字段(self)
    def clean_data_id(self):
        # 获取页面input框输入的资产编号
        data_id_txt = self.cleaned_data["data_id"]
        # 进入数据库,判断输入的资产编号是否存在
        # .exists() filter条件满足,则返回True
        exists = models.Asset.objects.filter(data_id=data_id_txt).exists()
        if exists:
            raise ValidationError("该资产已经被借用")
        # 如果资产编号不在数据库,则返回编号
        return data_id_txt


# 增加资产信息
def add_asset(request):
    title = "添加资产"
    if request.method == "GET":
        form = Addasset()
        return render(request, "asset_data/add_modify.html", {"title": title, "form": form})

    form = Addasset(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/asset/data/")
    return render(request, "asset_data/add_modify.html", {"title": title, "form": form})


class Modifyasset(forms.ModelForm):
    data_time = forms.CharField(disabled=True, label="借用时间")

    class Meta:
        model = models.Asset
        fields = "__all__"

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "autocomplete": "off"}

    def clean_data_id(self):
        # 获取页面input框输入的资产编号
        data_id_txt = self.cleaned_data["data_id"]
        # 进入数据库,判断输入的资产编号是否存在
        # .exists() filter条件满足,则返回True
        # exclude(id=self.instance.pk) 忽略当前字段,你某个值的验证
        exists = models.Asset.objects.exclude(id=self.instance.pk).filter(data_id=data_id_txt).exists()
        if exists:
            raise ValidationError("该资产已经被借用,请重新修改")
        # 如果资产编号不在数据库,则返回编号
        return data_id_txt


# 修改信息
def modify_asset(request, nid):
    title = "编辑资产信息"
    data_obj = models.Asset.objects.filter(id=nid).first()
    if request.method == "GET":
        form = Modifyasset(instance=data_obj)
        return render(request, "asset_data/add_modify.html", {"title": title, "form": form})

    form = Modifyasset(data=request.POST, instance=data_obj)
    if form.is_valid():
        form.save()
        return redirect("/asset/data/")
    return render(request, "asset_data/add_modify.html", {"title": title, "form": form})


# 删除操作
def delete_asset(request, nid):
    models.Asset.objects.filter(id=nid).delete()
    return redirect("/asset/data/")

asset_data/asset_data.html

{% extends "index/index.html" %}


{% block content %}
    <div class="container">
        <div style="margin-bottom: 10px">
                <a class="btn btn-success" href="/add/asset/"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span>添加资产</a>
                <div style="float: right;width: 300px">
                    <form method="get">
                    <div class="input-group">
                        <input type="text" class="form-control" placeholder="请输入资产编号" name="search">
                        <span class="input-group-btn">
                        <button class="btn btn-default" type="submit">Go!</button>
                        </span>
                    </div>
                </form>
                </div>


            </div>
            <div class="panel panel-warning">
                <div class="panel-heading">
                    <h3 class="panel-title">资产表</h3>
                </div>

                <div class="panel-body">
                    <table class="table">
                        <thead>
                        <tr>
                            <th>id</th>
                            <th>姓名</th>
                            <th>电话</th>
                            <th>借用日期</th>
                            <th>资产编号</th>
                            <th>归还状态</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for data in data_list %}
                            <tr>
                            <th>{{ data.id }}</th>
                            <td>{{ data.name }}</td>
                            <td>{{ data.mobile }}</td>
                            <td>{{ data.data_time }}</td>
                            <td>{{ data.data_id }}</td>
                            {% if data.ret_data == 1 %}
                                <td style="color: green">{{ data.get_ret_data_display }}</td>
                            {% else %}
                                <td style="color: red">{{ data.get_ret_data_display }}</td>
                            {% endif %}
                            <td>
                                <a href="/modify/{{ data.id}}/asset/"><span style="color: green" class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
                                <a href="/delete/{{ data.id}}/asset/"><span style="color: red" class="glyphicon glyphicon-trash" aria-hidden="true"></span></a>
                            </td>

                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
      <ul class="pagination">
          {{ page_string }}
      </ul>
    </div>
{% endblock %}

搜索与分页笔记:

搜索

models.Asset.objects.filter(name="Sakura",id=1)
  • 整数搜索

    # 搜索id为1的数据
    models.Asset.objects.filter(id=1)
    ​
    # 搜索id大于1的数据
    models.Asset.objects.filter(id__gt=1)
    ​
    # 搜索id大于等于1的数据
    models.Asset.objects.filter(id__gte=1)
    ​
    # 搜索id小于1的数据
    models.Asset.objects.filter(id__lt=1)
    ​
    # 搜索id小于等于1的数据
    models.Asset.objects.filter(id__lte=1)
  • 字符串搜索

    # 包含在内
    models.Asset.objects.filter(data_id__contains="2024")
    # 搜索开头
    models.Asset.objects.filter(data_id__startswidth="2024")
    # 搜索结尾
    models.Asset.objects.filter(data_id__endswidth="2024")

分页

1、每一页展示10条数据
	models.Asset.objects.filter(**dict_data)[0~9]    第一页
	models.Asset.objects.filter(**dict_data)[10~19]  第二页
	models.Asset.objects.filter(**dict_data)[20~29]  第一页
2、计算数据表总共有多少条数据:
	page = 500 / 10   (50页)
	page = 501 / 10   (51页)
3、页面只展示五个li标签
	如果在第一页, 则展示1,2,3,4,5
	如果在第三页, 则展示1,2,3,4,5
	如果在第四页, 则展示2,3,4,5,6
	
	如果总页数小于5页
		开始页 1
		结束页  总页数
	否则
		如果当前选择的是第一页或者第二页
            开始页=1
            结束页=5
         如果总共有20页
         	16,17,18,19,20
         否则,在其他页面
         	比如点到了第九页
         	开始页 = page - plue
         	结束页 = page + plue
		

上一篇:数据结构——树


下一篇:[MySQL最详细的知识点]