一、Django的序列化(对于ajax请求)
Django中的序列化主要应用在将数据库中检索的数据返回给客户端用户,特别的Ajax请求一般返回的为Json格式。
1)django序列化的使用方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1、serializers from django.core import serializers ret = models.BookType.objects.all() data = serializers.serialize("json", ret) 2、json.dumps import json #ret = models.BookType.objects.all().values('caption') ret = models.BookType.objects.all().values_list('caption') ret=list(ret) result = json.dumps(ret) 3、由于json.dumps时无法处理datetime日期,所以可以通过自定义处理器来做扩展,如: import json from datetime import date from datetime import datetime class JsonCustomEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, datetime): return o.strftime('%Y-%m-%d %H:%M:%S') elif isinstance(field, date): return o.strftime('%Y-%m-%d') else: return json.JSONEncoder.default(self, field)
2)当不使用序列化时的使用方法示例
视图函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def xuliehua1(request): return render(request,'xuliehua1.html')
对应的前端网页
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户列表</h1> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function() { initData(); }) function initData(){ $.ajax({ url:'/get_data1/', type:'GET', success:function(arg) { $('#tb').append(arg); } }) } </script> </body> </html>
对应的ajax请求的视图函数
def get_data1(request): user_list = models.UserInfo.objects.all() return render(request,'get_data1.html',{'user_list':user_list})
get_data1对应返回到ajax的网页信息
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{% for row in user_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.email }}</td> </tr> {% endfor %}
url(r'^xuliehua1/', v3.xuliehua1),
url(r'^get_data1/', v3.get_data1),
显示结果
如果返回的数据特别大,这种方式就会出现问题
3)django的序列化serializers,序列化QuesySet的对象
视图函数对应
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def xuliehua2(request): return render(request,'xuliehua2.html') def get_data2(request): from django.core import serializers ret = {'status':True,'data':None} try: user_list = models.UserInfo.objects.all() # user_list是django的 QuesySet 的对象[obj,obj,obj],序列化只能serializers ret['data'] = serializers.serialize("json",user_list) except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
对应的前端网页
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户列表</h1> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function() { initData(); }) function initData(){ $.ajax({ url:'/get_data2/', type:'GET', dataType:'JSON', success:function(arg) { if(arg.status){ var v = JSON.parse(arg.data) console.log(v) } } }) } </script> </body> </html>
4)json序列化方式
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def xuliehua3(request): return render(request,'xuliehua3.html') def get_data3(request): ret = {'status':True,'data':None} try: user_list = models.UserInfo.objects.all().values('id','username') # values 和 values_list一样的 ret['data'] = list(user_list) except Exception as e: ret['status'] = False result = json.dumps(ret) return HttpResponse(result)
对应的前端网页
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1>用户列表</h1> <table id="tb"> </table> <script src="/static/jquery-3.1.1.js"></script> <script> $(function() { initData(); }) function initData(){ $.ajax({ url:'/get_data3/', type:'GET', dataType:'JSON', success:function(arg) { if(arg.status){ console.log(arg.data) } } }) } </script> </body> </html>
二、上传文件
1)实现上传文件
html文件编写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload.html" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user"> <input type="file" name="img"> <input type="submit" value="提交"> </form> </body> </html>
视图函数编写
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def upload(request): if request.method == 'GET': return render(request,'upload.html') else: user = request.POST.get('user') img = request.FILES.get('img') # img是对象(文件大小,文件名称,文件内容。。。) print(img.name) print(img.size) f = open(img.name,'wb') for line in img.chunks(): f.write(line) f.close() return HttpResponse('...')
2)优化装饰上传文件的html文件。上传按钮隐藏,其他标签覆盖在上传按钮上
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/upload.html" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" name="user" /> <div style="position: relative"> <a>NB上传</a> <input type="file" name="img" style="opacity: 0;position:absolute;top:0;left: 0;" /> </div> <input type="submit" value="提交" /> </form> </body> </html>
3)基于form 做上传
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django import forms from django.forms import fields class UploadForm(forms.Form): user = fields.CharField() img = fields.FileField() def upload(request): if request.method == 'GET': return render(request,'upload.html') else: obj = UploadForm(request.POST,request.FILES) if obj.is_valid(): user = obj.cleaned_data['user'] img = obj.cleaned_data['img'] # img是对象(文件大小,文件名称,文件内容。。。) print(img.name) print(img.size) f = open(img.name,'wb') for line in img.chunks(): f.write(line) f.close() return HttpResponse('...')
4)Iframe+Form,实现上传文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .btn{ display: inline-block; padding: 5px 10px; background-color: coral; color: white; } </style> </head> <body> <iframe style="display: none" id="iframe1" name="ifra1"></iframe> <form id="fm1" action="/upload_img.html" method="POST" enctype="multipart/form-data" target="ifra1"> <input type="file" name="k3" onchange="uploadFile();" /> </form> <h3>预览</h3> <div id="preview"> </div> <script src="/static/js/jquery-3.1.1.js"></script> <script> function uploadFile() { document.getElementById('iframe1').onload = reloadIframe1; document.getElementById('fm1').submit(); } function reloadIframe1() { var content = this.contentWindow.document.body.innerHTML; var obj = JSON.parse(content); var tag = document.createElement('img'); tag.src = obj.data; $('#preview').empty().append(tag); } </script> </body> </html>
路由分发
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
url(r'^upload.html$', views.upload), url(r'^upload_img.html$', views.upload_img),
视图函数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
def upload(request): return render(request,'upload.html') def upload_img(request): import os import uuid nid = str(uuid.uuid4()) ret = {'status':True,'data':None,'message':None} obj = request.FILES.get('k3') file_path = os.path.join('static', nid+obj.name) f = open(file_path,'wb') for line in obj.chunks(): f.write(line) f.close() ret['data'] = file_path return HttpResponse(json.dumps(ret))