博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django 自定义分页器
阅读量:6396 次
发布时间:2019-06-23

本文共 16219 字,大约阅读时间需要 54 分钟。

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 += '
' 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 += '
' return tab_html,start_num,end_num

 

app01--> views

from django.shortcuts import render,HttpResponse,redirectimport osfrom django.contrib import authfrom app01.models import UserInfofrom crm import settingsfrom django.views import Viewfrom django import formsfrom app01 import modelsfrom django.utils.decorators import method_decoratorfrom 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 PageNationclass 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 myformclass 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 %}    

公共客户信息 展示

添加记录
{% csrf_token %}
{% for customer in all_customers %}
{% endfor %}
序号 qq 姓名 客户来源 咨询课程 选择客户此时的状态 销售 操作
{ { forloop.counter }} { { customer.qq }} { { customer.name }} { { customer.get_sex_display }} { { customer.course }} { { customer.get_status_display }} { { customer.consaltant.username|default:'暂无' }} 编辑 删除
{ { ret_html|safe }}
{% endblock %}{% block js %} {% endblock %}

 

转载于:https://www.cnblogs.com/zhangjian0092/p/11012847.html

你可能感兴趣的文章
Wannafly挑战赛9
查看>>
《企业云桌面实施》-小技巧-02-使用ISO光驱安装esxi6.5
查看>>
Python从菜鸟到高手(4):导入Python模块
查看>>
实战:Windows 2008 WDS使用参考计算机创建安装映像
查看>>
利用缓存来提高网站的性能(Caching to Improve the Performance of Your Website )
查看>>
Android应用程序注册广播接收器(registerReceiver)的过程分析
查看>>
对代理ARP技术的误读、无法完成代理ARP实验的故障分析
查看>>
详解网络流量监控
查看>>
可视化日志分析工具Gltail的安装与使用
查看>>
关于Segmentation fault (core dumped)几个简单问题
查看>>
经典SQL语句大全(基础篇)
查看>>
HTML5 Canvas眨眼睛动画
查看>>
C-C和指针作业题(第一章)
查看>>
[推荐]网店代销的卖家,你的宝贝名称修改了吗?
查看>>
Android NDK JNI C++ <7> eg
查看>>
jQuery打造智能提示插件二(可编辑下拉框)
查看>>
PHP中spl_autoload_register函数的用法
查看>>
[Python] Python 之 function, unbound method 和 bound method
查看>>
Linux makefile 教程 很具体,且易懂
查看>>
希尔排序
查看>>