django 自定义分页器

app01 --> page

#自定义分页
#官方推荐,页码数为奇数
class PageNation:
    def __init__(self,base_url,current_page_num,total_counts,request,per_page_counts=10,page_number=5,):
        '''
        :param base_url:   分页展示信息的基础路径
        :param current_page_num:  当前页页码
        :param total_counts:  总的数据量
        :param per_page_counts:  每页展示的数据量
        :param page_number:  显示页码数
        '''

        self.base_url = base_url
        self.current_page_num = current_page_num
        self.total_counts = total_counts
        self.per_page_counts = per_page_counts
        self.page_number = page_number
        self.request = request
        try:
            self.current_page_num = int(self.current_page_num)

        except Exception:
            self.current_page_num = 1
        if self.current_page_num < 1:
            self.current_page_num = 1

        half_page_range = self.page_number // 2
        # 计算总页数
        self.page_number_count, a = divmod(self.total_counts, self.per_page_counts)


        if a:
            self.page_number_count += 1


        if self.current_page_num > self.page_number_count:
            self.current_page_num = self.page_number_count

        if self.page_number_count <= self.page_number:
            self.page_start = 1
            self.page_end = self.page_number_count
        else:
            if self.current_page_num <= half_page_range:  #2
                self.page_start = 1
                self.page_end = page_number  #5
            elif self.current_page_num + half_page_range >= self.page_number_count:
                self.page_start = self.page_number_count - self.page_number + 1
                self.page_end = self.page_number_count
            else:
                self.page_start = self.current_page_num - half_page_range
                self.page_end = self.current_page_num + half_page_range


        import copy
        from django.http.request import QueryDict

        self.params = copy.deepcopy(request.GET)

        # ?condition = qq & wd = 1 & page = 3
        # params['page'] = current_page_num
        # query_str = params.urlencode()
    #数据切片依据,起始位置
    @property
    def start_num(self):
        start_num = (self.current_page_num - 1) * self.per_page_counts
        return start_num

    #数据切片依据,终止位置
    @property
    def end_num(self):
        end_num = self.current_page_num * self.per_page_counts
        return end_num

    # 拼接HTMl标签
    def page_html(self):
        tab_html = ''
        tab_html += '<nav aria-label="Page navigation" class="pull-right"><ul class="pagination">'
        #首页
        self.params['page'] = 1
        showye = '<li><a href="{0}?{1}" aria-label="Previous" ><span aria-hidden="true">首页</span></a></li>'.format(self.base_url,self.params.urlencode())
        tab_html += showye
        # 上一页
        if self.current_page_num == 1:
            previous_page = '<li disabled><a href="#" aria-label="Previous" ><span aria-hidden="true">&laquo;</span></a></li>'
        else:
            self.params['page'] = self.current_page_num - 1
            previous_page = '<li><a href="{0}?{1}" aria-label="Previous" ><span aria-hidden="true">&laquo;</span></a></li>'.format(
                self.base_url,self.params.urlencode())
        tab_html += previous_page

        #循环生成页码标签
        for i in range(self.page_start, self.page_end + 1):
            # request.GET  {condition: qq, wd: 1,'page':1} request.GET.urlencode() condition=qq&wd=1&page=4

            self.params['page'] = i # {condition: qq, wd: 1,'page':1} urlencode() -- condition=qq&wd=1&page=4

            if self.current_page_num == i:

                one_tag = '<li class="active"><a href="{0}?{2}">{1}</a></li>'.format(self.base_url, i,self.params.urlencode()) #?condition=qq&wd=1&page=3
            else:
                one_tag = '<li><a href="{0}?{2}">{1}</a></li>'.format(self.base_url, i,self.params.urlencode())
            tab_html += one_tag

        # 下一页
        if self.current_page_num == self.page_number_count:
            next_page = '<li disabled><a href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'
        else:
            self.params['page'] = self.current_page_num + 1
            next_page = '<li><a href="{0}?{1}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(self.base_url, self.params.urlencode())
        tab_html += next_page

        # 尾页
        self.params['page'] = self.page_number_count
        weiye = '<li><a href="{0}?{1}" aria-label="Previous" ><span aria-hidden="true">尾页</span></a></li>'.format(
            self.base_url, self.params.urlencode())

        tab_html += weiye
        tab_html += '</ul></nav>'

        return tab_html


#函数low鸡版
def pagenation(base_url,current_page_num,total_counts,per_page_counts=10,page_number=5):
    '''
    total_counts数据总数
    per_page_counts每页分多少条数据
    page_number = 页码显示多少个
    current_page_num 当前页
    :return:
    '''
    # all_objs_list = models.Customer.objects.all()
    # total_counts = all_objs_list.count()
    # page_number = 5

    try:
        current_page_num = int(current_page_num)

    except Exception:
        current_page_num = 1


    half_page_range = page_number//2
    #计算总页数
    page_number_count,a = divmod(total_counts,per_page_counts)
    if current_page_num < 1:
        current_page_num = 1

    if a:
        page_number_count += 1
    if current_page_num > page_number_count:
        current_page_num = page_number_count

    start_num = (current_page_num - 1) * 10
    end_num = current_page_num * 10

    if page_number_count <= page_number:
        page_start = 1
        page_end = page_number_count
    else:
        if current_page_num <= half_page_range:
            page_start = 1
            page_end = page_number
        elif current_page_num + half_page_range  >= page_number_count:
            page_start = page_number_count - page_number + 1
            page_end = page_number_count
        else:
            page_start = current_page_num - half_page_range
            page_end = current_page_num + half_page_range

    #拼接HTMl标签
    tab_html = ''
    tab_html += '<nav aria-label="Page navigation"><ul class="pagination">'

    #上一页
    if current_page_num == 1:
        previous_page = '<li disabled><a href="#" aria-label="Previous" ><span aria-hidden="true">&laquo;</span></a></li>'
    else:
        previous_page = '<li><a href="{0}?page={1}" aria-label="Previous" ><span aria-hidden="true">&laquo;</span></a></li>'.format(base_url,current_page_num-1)
    tab_html += previous_page

    for i in range(page_start,page_end+1):
        if current_page_num == i:

            one_tag = '<li class="active"><a href="{0}?page={1}">{1}</a></li>'.format(base_url,i)
        else:
            one_tag = '<li><a href="{0}?page={1}">{1}</a></li>'.format(base_url, i)
        tab_html += one_tag


    #下一页
    if current_page_num == page_number_count:
        next_page = '<li disabled><a href="#" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'
    else:
        next_page = '<li><a href="{0}?page={1}" aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>'.format(base_url,current_page_num+1)
    tab_html+=next_page
    tab_html += '</ul></nav>'

    return tab_html,start_num,end_num

app01--> views

from django.shortcuts import render,HttpResponse,redirect
import os
from django.contrib import auth
from app01.models import UserInfo
from crm import settings
from django.views import View
from django import forms
from app01 import models
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
# Create your views here.



class RegForm(forms.Form):
    username = forms.CharField(
        label='用户名',
        max_length=12,
        min_length=6,
        error_messages={
            'max_length':'用户名不能超过12位',
            'min_length':'用户名不能低于6位',
            'required':'用户名不能为空',
        }
    )
    password = forms.CharField(
        label='密码',
        max_length=16,
        min_length=6,
        error_messages={
            'max_length': '密码不能超过12位',
            'min_length': '密码不能低于6位',
            'required': '密码不能为空',
        },
        widget=forms.widgets.PasswordInput(render_value=True),

    )

    r_password = forms.CharField(
        label='密码',
        max_length=16,
        min_length=6,
        error_messages={
            'max_length': '密码不能超过12位',
            'min_length': '密码不能低于6位',
            'required': '密码不能为空',
        },
        widget=forms.widgets.PasswordInput,

    )



    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for field in self.fields:
            self.fields[field].widget.attrs.update({'class':'form-control'})

def get_valid_img(request):

    from PIL import Image
    #终极版,方式5
    import random
    def get_random_color():
        return (random.randint(0,255),random.randint(0,255),random.randint(0,255))
    from PIL import Image,ImageDraw,ImageFont
    img_obj = Image.new('RGB', (236, 34), get_random_color()) #图片对象
    draw_obj = ImageDraw.Draw(img_obj)  #通过图片对象生成一个画笔对象
    font_path = os.path.join(settings.BASE_DIR,'statics/font/ziti.TTF') #获取字体,注意有些字体文件不能识别数字,所以如果数字显示不出来,就换个字体
    font_obj = ImageFont.truetype(font_path,16) #创建字体对象
    sum_str = ''  #这个数据就是用户需要输入的验证码的内容
    for i in range(6):
        a = random.choice([str(random.randint(0,9)), chr(random.randint(97,122)), chr(random.randint(65,90))])  #4  a  5  D  6  S
        sum_str += a
    # print(sum_str)
    draw_obj.text((84,10),sum_str,fill=get_random_color(),font=font_obj) #通过画笔对象,添加文字

    width=236
    height=34
    # 添加噪线
    for i in range(5): #添加了5条线
        #一个坐标表示一个点,两个点就可以连成一条线
        x1=random.randint(0,width)
        x2=random.randint(0,width)
        y1=random.randint(0,height)
        y2=random.randint(0,height)
        draw_obj.line((x1,y1,x2,y2),fill=get_random_color())
    # # 添加噪点
    for i in range(10):
        #这是添加点,50个点
        draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=get_random_color())
        #下面是添加很小的弧线,看上去类似于一个点,50个小弧线
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw_obj.arc((x, y, x + 4, y + 4), 0, 90, fill=get_random_color()) #x, y是弧线的起始点位置,x + 4, y + 4是弧线的结束点位置

    from io import BytesIO
    f = BytesIO()  #操作内存的把手
    img_obj.save(f,'png')  #
    data = f.getvalue()

    # 存这个验证码的方式1:赋值给全局变量的简单测试
    # global valid_str
    # valid_str = sum_str
    # 方式2:将验证码存在各用户自己的session中,session的应用其实还有很多
    request.session['valid_str'] = sum_str
    return HttpResponse(data)


class Login(View):
    def get(self,request):
        return render(request,'login.html')
    def post(self,request):
        data = request.POST
        if data.get('code') == request.session['valid_str']:
            user_obj = auth.authenticate(username=data.get('username'),password=data.get('password'))
            if user_obj:
                auth.login(request,user_obj)
                return redirect('index')
            else:
                return redirect('login')
        else:
            return render(request,'login.html')

class Register(View):
    def get(self, request):
        form_obj = RegForm()
        return render(request, 'register.html',{"form_obj":form_obj})
    def post(self,request):
        data = request.POST
        form_obj = RegForm(data)
        code = data.get('code')
        error = ''
        if code == request.session['valid_str']:
            if data.get('password') == data.get('r_password'):
                if form_obj.is_valid():
                    user_obj = UserInfo.objects.create_user(username=data.get('username'),password=data.get('password'))
                    return redirect('login')
            else:
                erro = '两次密码不一致'
        else:
            erro = '验证码错误'
        return render(request, 'register.html',{"form_obj":form_obj,'error':erro})

#
from app01.page import PageNation
class Index(View):
    @method_decorator(login_required())
    def dispatch(self, request, *args, **kwargs):
        ret = super(Index, self).dispatch(request,*args,**kwargs)
        return ret

    def get(self,request):

        all_costomer = models.Customer.objects.all()
        #self,base_url,current_page_num,total_counts,per_page_counts=10,page_number=5
        costomer_obj = PageNation(request.path,request.GET.get('page'),all_costomer.count())
        start_num = costomer_obj.start_num
        end_num = costomer_obj.end_num
        page_html = costomer_obj.page_html()
        # print(page_html)
        costomers = all_costomer[start_num:end_num]
        return render(request,'index.html',{'all_costomer':costomers,'page_html':page_html})

    def post(self,request):
        condition = request.POST.get('condition')
        wd = request.POST.get('wd')
        print('condition:wd',condition,wd)
        from django.db.models import Q
        q = Q()
        q.children.append((condition,wd))
        print('q',q)

# @login_required()
# def index(request):
#     return render(request,'index.html')

class Logout(View):

    def get(self,request):
        auth.logout(request)
        return redirect('login')

class Start(View):

    def get(self,request):
        return render(request,'starter.html')


from app01 import myform
class Addcostomer(View):
    def get(self,request):
        customerform = myform.CustomerForm()
        return render(request,'addcustomer.html',{'customerform':customerform})


    def post(self,request):
        data = request.POST
        customerform = myform.CustomerForm(data)
        if customerform.is_valid():
            customerform.save()
            return redirect('index')
        else:
            return render(request,'index.html',{'customerform':customerform})

class Edicustomer(View):

    def get(self,request,pk):
        # print(pk)
        customer_obj = models.Customer.objects.get(pk=pk)
        customer_form = myform.CustomerForm(instance=customer_obj)
        return render(request,'edicustomer.html',{'customerform':customer_form})

    def post(self,request,pk):
        customer_obj = models.Customer.objects.get(pk=pk)
        customer_form = myform.CustomerForm(request.POST,instance=customer_obj)
        if customer_form.is_valid():
            customer_obj.save()
            return redirect('index')
        else:
            return render(request,'edicustomer.html', {'customerform':customer_form})

class Delcustomer(View):
    def get(self,request,pk):
        # print(pk)
        models.Customer.objects.filter(pk=pk).delete()
        return redirect('index')

class FilterCustomer(View):
    def get(self,request):
        pass
        # return render(request,'filtercustomer.html',{'all_customer':all_customer})


from app01 import page2
#老师讲的 ,带分页效果的客户信息展示
class Customers(View):
    def get(self,request):
        wd = request.GET.get('wd','')
        condition = request.GET.get('condition','')

        #筛选公共用户
        all_customers = models.Customer.objects.filter(consultant__isnull=True)

        from django.db.models import Q
        if wd:  #如果有筛选条件
            q = Q()
            q.children.append((condition,wd))

            #将公共用户根据筛选条件再次进行筛选
            all_customers = all_customers.filter(q)

        per_page_counts = 5
        page_number = 11
        total_count = all_customers.count()
        current_page_num = request.GET.get('page',1)

        #通过分页类实例化一个 分页对象
        page_obj = page2.PageNation(request.path, current_page_num, total_count, request,per_page_counts,page_number)

        all_customers = all_customers.order_by('-pk')[page_obj.start_num:page_obj.end_num]
        # all_customers = all_customers.order_by('-pk')[page_obj.start_num, page_obj.end_num]

        ret_html = page_obj.page_html()

        return render(request,'customers.html', {'all_customers':all_customers,'ret_html':ret_html})


    def post(self,request):
        self.data = request.POST.getlist('selected_id')
        print(self.data)
        action = request.POST.get('action')
        if hasattr(self,action):
            func = getattr(self,action)
            if callable(func):
                func(request)
                return redirect('customers')
            else:
                return HttpResponse('别动')
        else:
            return HttpResponse('不要搞事情')


    def batch_delete(self,request):
        models.Customer.objects.filter(pk__in=self.data).delete()

    def batch_update(self,request):
        models.Customer.objects.filter(pk__in=self.data).update(name='熊哥')

    def batch_reverse_gs(self,request):
        models.Customer.objects.filter(pk__in=self.data).update(consultant=request.user)

templete --> customer.html

{% extends 'starter.html' %}

{% block content %}
    <div class="content-wrapper">
         <section class="content-header">
            <h1>
                公共客户信息
                <small>展示</small>
            </h1>

            <ol class="breadcrumb">
                <li><a href="#"><i class="fa fa-dashboard"></i> Level</a></li>
                <li class="active">Here</li>
            </ol>
        </section>

        <section class="content catainer-fluid">
            <div class="row">
                <div class="col-xs-12">
                    <div class="box">

                        <form action="" method="get" class="pull-right" style=" 400px;display: inline-block">
                            <select name="condition" id="" class="form-control" style=" 100px;display: inline-block">
                                <option value="name__contains">姓名</option>
                                <option value="qq__contains">QQ</option>
                            </select>
                            <input type="text" name="wd" class="form-control" style=" 200px;display: inline-block">
                            <button class="btn btn-default">搜索</button>
                        </form>
                        <a href="" class="btn btn-primary pull-right">添加记录</a>


                        <form action="" method="post">
                            {% csrf_token %}
                            <select name="action" id="" class="form-control" style=" 200px;display: inline-block">
                                <option value="batch_delete">批量删除</option>
                                <option value="batch_update">批量更新客户状态</option>
                                <option value="batch_reverse_gs">批量公户转私户</option>
                            </select>
                            <button class="btn btn-danger" style="vertical-align: 1px;">go</button>


                        <div class="box-body">
                            <table class="table table-bordered table-hover">
                                <thead>
                                    <tr>
                                        <th>
                                            <input type="checkbox" id="choose" class="choose">
                                        </th>
                                        <th>序号</th>
                                        <th>qq</th>
                                        <th>姓名</th>
                                        <th>客户来源</th>
                                        <th>咨询课程</th>
                                        <th>选择客户此时的状态</th>
                                        <th>销售</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    {% for customer in all_customers %}
                                        <tr>
                                            <td><input type="checkbox" name="selected_id" value="{{ customer.pk }}"></td>
                                            <td>{{ forloop.counter }}</td>
                                            <td>{{ customer.qq }}</td>
                                            <td>{{ customer.name }}</td>
                                            <td>{{ customer.get_sex_display }}</td>
                                            <td>{{ customer.course }}</td>
                                            <td>{{ customer.get_status_display }}</td>
                                            <td>{{ customer.consaltant.username|default:'暂无' }}</td>
                                            <td>
                                                <a href="" class="btn btn-warning">编辑</a>
                                                <a href="" class="btn btn-danger">删除</a>
                                            </td>

                                        </tr>


                                    {% endfor %}

                                </tbody>

                            </table>

                            {{ ret_html|safe }}
                        </div>

                        </form>




                    </div>

                </div>
            </div>

        </section>

    </div>



{% endblock %}

{% block js %}
    <script>
        $('#choose').click(function(){
        var status = $(this).prop('checked');
        $('[name=selected_id]').prop('checked',status);
{#        if (status === true){#}
{#            $('[name=selected_id]').prop('checked',true);#}
{##}
{#        }#}
{#        else{#}
{#            $('[name=selected_id]').prop('checked',false);#}
{#        }#}
    })
    </script>

{% endblock %}
原文地址:https://www.cnblogs.com/zhangjian0092/p/11012847.html