django框架之Ajax,自定义分页器...
MTV与MVC
MTV模型(django):
M:模型层(models.py)
T:模板层(templates)
V:视图层(views.py)
MVC模型:
M:模型层(models.py)
V:视图层(views.py)
C:控制器(Controller) urls.py
本质:django的MTV也是MVC
多对多表三种创建方式
1. django orm 自动创建
class Book(models.Model): name = models.CharField(max_length=32) authors = models.ManyToManyField(to='Author') class Author(models.Model): name = models.CharField(max_length=32)
2. 手动创建第三张表
class Book(models.Model): name = models.CharField(max_length=32) class Author(models.Model): name = models.CharField(max_length=32) class Book2Author(models.Model): book = models.ForeignKey(to='Book') author = models.ForeignKey(to='Author') info = models.CharField(max_length=32)
3. 半自动创建第三张表:可扩展性高,并且能够符合orm查询
class Book(models.Model): name = models.CharField(max_length=32)
# 表自身相关字段名放前面 authors = models.ManyToManyField(to='Author',through='Book2Author',through_fields=('book','author'))
class Author(models.Model): name = models.CharField(max_length=32) # book = models.ManyToManyField(to='Book',through='Book2Author',through_fields=('author','book')) class Book2Author(models.Model): book = models.ForeignKey(to='Book') author = models.ForeignKey(to='Author') info = models.CharField(max_length=32)
前后端传输数据编码格式contentType
urlencoded
对应的数据格式:name=jason&password=666
后端获取数据:request.POST
ps:django会将urlencoded编码的数据解析自动放到request.POST
formdata
form表单传输文件的编码格式
后端获取文件格式数据:request.FILES
后端获取普通键值对数据:request.POST
application/json
ajax发送json格式数据
注意:编码与数据格式要一致
关于AJAX
AJAX:Asynchronous Javascript And XML,异步的JavaScript和XML;
即使用JavaScript语言与服务器进行异步交互,传输的数据为XML(不只是XML)。
是一种使用现有标准的新方法,最大的优点:不重新加载整个页面的情况下,与服务器交换数据并更新部分网页内容
1. 前端有哪些方式可以向后端发送请求
浏览器窗口输入网址 get请求
a标签的href属性 get请求
form表单 get/post请求(默认是get请求)
ajax get/post请求
2. Ajax特点:
异步提交
局部刷新
3. Ajax基本语法
提交的地址:不写,默认当前页面打开的地址
提交的方式
数据的格式:contentType,后端接收request.body
提交的数据
回调函数
<script> $('#d1').click(function(){ $.ajax({ url:'/index/', type:'post', contentType:'application/json', data:{'name':'jason','password':'123'}, success:function(data){ # data接收的就是异步提交返回的结果 alert(data) } }) }) </script>
注意:
默认传输数据的编码格式:urlencoded
前后端传输数据,数据是什么格式,就告知相应格式(数据与编码要一一对应)
4. Ajax传输json格式数据
JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation),一种文本数据交换格式,
JSON 独立于语言和平台,只认{[双引号的字符串]}格式
urlencoded 默认传出编码格式,Ajax的简单用法
<input type="text" id="i1">+ <input type="text" id="i2">= <input type="text" id="i3"> <button id="d1">加➕</button> <script> $('#d1').click(function () { $.ajax({ url:'', type:'post', data:{'i1':$('#i1').val(),'i2':$('#i2').val()}, success:function (data) { $('#i3').val(data) } }) }); </script>
def index(request): if request.method == 'POST': print(request.POST) i1 = request.POST.get("i1") # str格式,需要数字需要强转一下 i2 = request.POST.get("i2") res = i1 + i2 return HttpResponse(res) return render(request, 'index.html')
application/json 传输数据:
$('#d1').click(function () { $.ajax({ url:'', // url参数可以不写,默认就是当前页面打开的地址 type:'post', contentType:'application/json', data:JSON.stringify({'name':'jason','hobby':'study'}), success:function (data) { alert('ok') } }) });
后端接收数据的,在request.body里面,没有做处理,还是二进制编码格式b''
def index(request): if request.method == 'POST': print(request.body) data = request.body # b'{"name":"json","hobby":"study"}'
res = data.decode('utf-8') # 解码方式1 res1 = json.loads(res) print(res1, type(res1)) # {'name': 'json', 'hobby': 'study'} <class 'dict'>
res2 = str(data, encoding='utf-8') # 解码方式2
print(res2, type(res2)) # {"name":"json","hobby":"study"} <class 'str'>
return HttpResponse('RES') return render(request, 'index.html')
Ajax传输文件
$('#d1').click(function () { let formdata = new FormData(); // FormData对象不仅仅可以传文件还可以传普通的键值对 formdata.append('name','jason'); // 获取input框存放的文件 //$('#i1')[0].files[0] formdata.append('myfile',$('#i1')[0].files[0]); $.ajax({ url:'', type:'post', data:formdata, // ajax发送文件需要修改两个固定的参数 processData:false, // 告诉浏览器不要处理我的数据 contentType:false, // 不要用任何的编码,就用我formdata自带的编码格式,django能够自动识别改formdata对象 // 回调函数 success:function (data) { alert(data) } }) });
5. form表单与ajax异同点
1.form表单不支持异步提交局部刷新
2.form表单不支持传输json格式数据
3.form表单与ajax默认传输数据的编码格式都是urlencoded
自定义分页器
1. 批量插入数据
bulk_create批量插入数据,与create一个个创建数据相比,不用每产生一个数据就执行的sql语句,速度会快很多
l = [] for i in range(10000): l.append(models.Book2(name='第%s本书'%i)) models.Book.objects.bulk_create(l) # 批量插入数据
2. 必要的参数
后端:
获取所有数据 book_list = models.Book2.objects.all()
数据总条数 all_count = book_list.count()
当前页 current_page = request.GET.get('page',1)
实例化分页器对象 page_obj = my_page.Pagination(current_page=current_page,all_count=all_count)
对总数据进行切片 page_queryset = book_list[page_obj.start:page_obj.end]
前端:
{{ page_obj.page_html|safe }} # 渲染带有bootstrap样式的分页器
<li><a href="?page=1">1</a></li> # 自动补全当前路径
3. 注意点
需要加首页尾页
显示的页码数应该是固定的
单数显示页面,比较具有对称美感
4. 分页器推导过程
def booklist(request): all_count = models.Book2.objects.all().count() current_page = request.GET.get('page', 1) current_page = int(current_page) per_page_num = 10 page_nums, more = divmod(all_count, per_page_num) if more: page_nums += 1 html = '' for i in range(1, page_nums+1): html += '<li><a href="?page=%s">%s</a></li>' % (i, i) page_start = (current_page-1)*per_page_num page_end = current_page*per_page_num book_list = models.Book2.objects.all()[page_start:page_end] return render(request, 'booklist.html', locals())
会将所有页码显示于同一页(┬_┬)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <table class="table table-hover table-bordered table-striped"> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> {% for book in book_list %} <tr> <td>{{ book.pk }}</td> <td>{{ book.name }}</td> </tr> {% endfor %} </tbody> </table> <nav aria-label="Page navigation"> <ul class="pagination"> <li> <a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> {{ html|safe }} <li> <a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> </ul> </nav> </div> </div> </div> </body> </html>
5. 分页器终极版本
class Pagination(object): def __init__(self, current_page, all_count, per_page_num=2, pager_count=11): """ 封装分页相关数据 :param current_page: 当前页 :param all_count: 数据库中的数据总条数 :param per_page_num: 每页显示的数据条数 :param pager_count: 最多显示的页码个数 用法: queryset = model.objects.all() page_obj = Pagination(current_page,all_count) page_data = queryset[page_obj.start:page_obj.end] 获取数据用page_data而不再使用原始的queryset 获取前端分页样式用page_obj.page_html """ try: current_page = int(current_page) except Exception as e: current_page = 1 if current_page < 1: current_page = 1 self.current_page = current_page self.all_count = all_count self.per_page_num = per_page_num # 总页码 all_pager, tmp = divmod(all_count, per_page_num) if tmp: all_pager += 1 self.all_pager = all_pager self.pager_count = pager_count self.pager_count_half = int((pager_count - 1) / 2) @property def start(self): return (self.current_page - 1) * self.per_page_num @property def end(self): return self.current_page * self.per_page_num def page_html(self): # 如果总页码 < 11个: if self.all_pager <= self.pager_count: pager_start = 1 pager_end = self.all_pager + 1 # 总页码 > 11 else: # 当前页如果<=页面上最多显示11/2个页码 if self.current_page <= self.pager_count_half: pager_start = 1 pager_end = self.pager_count + 1 # 当前页大于5 else: # 页码翻到最后 if (self.current_page + self.pager_count_half) > self.all_pager: pager_end = self.all_pager + 1 pager_start = self.all_pager - self.pager_count + 1 else: pager_start = self.current_page - self.pager_count_half pager_end = self.current_page + self.pager_count_half + 1 page_html_list = [] # 添加前面的nav和ul标签 page_html_list.append(''' <nav aria-label='Page navigation>' <ul class='pagination'> ''') first_page = '<li><a href="?page=%s">首页</a></li>' % (1) page_html_list.append(first_page) if self.current_page <= 1: prev_page = '<li class="disabled"><a href="#">上一页</a></li>' else: prev_page = '<li><a href="?page=%s">上一页</a></li>' % (self.current_page - 1,) page_html_list.append(prev_page) for i in range(pager_start, pager_end): if i == self.current_page: temp = '<li class="active"><a href="?page=%s">%s</a></li>' % (i, i,) else: temp = '<li><a href="?page=%s">%s</a></li>' % (i, i,) page_html_list.append(temp) if self.current_page >= self.all_pager: next_page = '<li class="disabled"><a href="#">下一页</a></li>' else: next_page = '<li><a href="?page=%s">下一页</a></li>' % (self.current_page + 1,) page_html_list.append(next_page) last_page = '<li><a href="?page=%s">尾页</a></li>' % (self.all_pager,) page_html_list.append(last_page) # 尾部添加标签 page_html_list.append(''' </nav> </ul> ''') return ''.join(page_html_list)
def booklist(request): book_list = models.Book2.objects.all() all_count = book_list.count() current_page = request.GET.get('page', 1) page_obj = mypage.Pagination(current_page=current_page, all_count=all_count,per_page_num=10) page_queryset = book_list[page_obj.start:page_obj.end] return render(request, 'booklist.html', locals())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script> <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet"> <script src="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <table class="table table-hover table-bordered table-striped"> <thead> <tr> <th>id</th> <th>name</th> </tr> </thead> <tbody> {% for book in page_queryset %} <tr> <td>{{ book.pk }}</td> <td>{{ book.name }}</td> </tr> {% endfor %} </tbody> </table> {{ page_obj.page_html|safe }} </div> </div> </div> </body> </html>